PHP中的魔术方法
PHP中有下列称之为魔术方法(magic method)的函数:__construct, __destruct ,__call, __callStatic,__get, __set, __isset, __unset , __sleep, __wakeup,__toString, __set_state, __clone and __autoload,本文使用__call为实现一个身份验证的简单实例,代码如下:代码
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--><?php
interfaceAccountable
{
constERR_MSG="error";
publicfunctionisLoggedIn();
publicfunctiongetAccount($user='');
}
abstractclassAuthenticationimplementsAccountable
{
private$account=null;
publicfunctiongetAccount($user='')
{
if($this->account!=null){
return$this->account;
}else{
returnERR_MSG;
}
}
publicfunctionisLoggedIn()
{
return($this->account!=null);
}
}
classUsers
{
privatestatic$accounts=array('phinecos'=>'phine',
'guest'=>'guest'
);
publicstaticfunctionvalidates($user,$passwd)
{
returnself::$accounts[$user]==$passwd;
}
publicfunction__call($name,array$arguments)
{
if(preg_match("/^validates(.*)$/",$name,$matches)&&count($arguments)>0){
returnself::validates($matches[1],$arguments[0]);
}
}
}
classMyAuthextendsAuthentication
{
private$users;
publicfunction__construct()
{
$this->users=newUsers();
}
publicfunctionlogin($user,$passwd)
{
if(empty($user)||empty($passwd))returnfalse;
$firstValidation=Users::validates($user,$passwd);
$userFunction='validates'.$user;
$secondValidation=$this->users->$userFunction($passwd);
return($firstValidation&&$secondValidation);
}
}
functionmain()
{
$authenticator=newMyAuth();
$user='phinecos';
$pwd='phine';
$isValid=$authenticator->login($user,$pwd);
if($isValid){
echo'validuser';
}else{
echo'invaliduser';
}
}
main();
?>
页:
[1]