PHP中的魔术方法

本文通过实现一个简单的身份验证系统来展示PHP中魔术方法__call的功能。实例中定义了接口Accountable和抽象类Authentication,利用Users类中的__call方法进行用户名和密码验证。

PHP中有下列称之为魔术方法(magic method)的函数:__construct, __destruct , __call, __callStatic,__get, __set, __isset, __unset , __sleep, __wakeup, __toString, __set_state, __clone and __autoload,本文使用__call为实现一个身份验证的简单实例,代码如下:

ExpandedBlockStart.gif代码

<!--<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();
?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值