PHP中有下列称之为魔术方法(magic method)的函数:__construct, __destruct , __call, __callStatic,__get, __set, __isset, __unset , __sleep, __wakeup, __toString, __set_state, __clone and __autoload,本文使用__call为实现一个身份验证的简单实例,代码如下:
- <?php
- interface Accountable
- {
- const ERR_MSG = "error";
- public function isLoggedIn();
- public function getAccount($user = '');
- }
- abstract class Authentication implements Accountable
- {
- private $account = null;
- public function getAccount($user = '')
- {
- if ($this->account != null) {
- return $this->account;
- } else {
- return ERR_MSG;
- }
- }
- public function isLoggedIn()
- {
- return ($this->account != null);
- }
- }
- class Users
- {
- private static $accounts = array('phinecos' => 'phine',
- 'guest' => 'guest'
- );
- public static function validates($user, $passwd)
- {
- return self::$accounts[$user] == $passwd;
- }
- public function __call($name, array $arguments)
- {
- if (preg_match("/^validates(.*)$/", $name, $matches) && count($arguments) > 0) {
- return self::validates($matches[1], $arguments[0]);
- }
- }
- }
- class MyAuth extends Authentication
- {
- private $users;
- public function __construct()
- {
- $this->users = new Users();
- }
- public function login($user, $passwd)
- {
- if (emptyempty($user) || emptyempty($passwd)) return false;
- $firstValidation = Users::validates($user, $passwd);
- $userFunction = 'validates'.$user;
- $secondValidation = $this->users->$userFunction($passwd);
- return ($firstValidation && $secondValidation);
- }
- }
- function main()
- {
- $authenticator = new MyAuth();
- $user = 'phinecos';
- $pwd = 'phine';
- $isValid = $authenticator->login($user, $pwd);
- if ($isValid) {
- echo 'valid user';
- } else {
- echo 'invalid user';
- }
- }
- main();
- ?>