真实世界中的例子
既然你已经知道了PHP中的对象是如何工作的基础内容,那么让我们以一个真实世界中的例子对此进行总结。考虑下面的userAuth()类,其提供了使用加密密码文件(诸如,/etc/password或htaccess,这两者都用于Unix系统(亦即,互联网的大部分)中)来验证用户登录的方法。我在这里会假定密码文件中的密码采用MD5算法加密,然后使用以$1$开头的12位字符:
<?php // PHP 5 // class definition class userAuth { // define properties public $username; private $passwd; private $passwdFile; private $_resultCode; // constructor // must be passed username and password public function __construct($username, $password) { $this->username = $username; $this->passwd = $password; $this->_resultCode = -1; } // used to set file to read for password data public function setPasswdFile($file) { $this->passwdFile = $file; } // returns: -1 if user does not exist // 0 if user exists but password is incorrect // 1 if username and password are correct public function getResultCode() { return $this->_resultCode; } public function authenticateUser() { // make sure that the script has permission to read this file! $data = file($this->passwdFile); // iterate through file foreach ($data as $line) { $arr = explode(":", $line); // if username matches // test password if ($arr[0] == $this->username) { // if match, user/pass combination is correct // return 1 if ($arr[1] == crypt($this->passwd, $arr[1])) { $this->_resultCode = 1; break; } // otherwise return 0 else { $this->_resultCode = 0; break; } } } } // end class definition } ?>
通过前面几页中的例子,这例子中的大部分对你来说应该是清楚的。如果你还不清楚,那么下列脚本将帮助你理解正在发生的:
<?php // create instance $ua = new userAuth("joe", "secret"); // set password file $ua->setPasswdFile("passwd.txt"); // perform authentication $ua->authenticateUser(); // check result code and display message switch ($ua->getResultCode()) { case -1: echo "Could not find your user account"; break; case 0: echo "Your password was incorrect"; break; case 1: echo "Welcome, ".$ua->username; break; } ?>
这里,用户名和密码被传递给对象的构造器,包含认证凭证的文件名称和路径也同样传递给对象的构造器。authenticateUser()方法负责解析密码文件,然后检查用户是否存在以及密码是否正确。取决于它所发现的结果而产生一个结果码并且将其保存在私有变量$_resultCode中。这个变量可以通过getResultCode()方法来读取,然后显示一条适当的信息。因为整个验证都整洁地封装在一个类中,所以我可以带他到任何地方,在任何脚本中对其进行使用(甚至在其他应用软件中),而且对它进行扩展以支持不同类型的认证模式和容器。
你还可以对对象做更多的操作,尤其是在PHP 5中;我已经将自己限制在这里,因为我不想让你因为讨论过载、抽象类和静态方法而太困惑
在第八章的学习,我将向你展示如何将你的脚本连接至MySQL数据库。