+-------------------------------------------------------------------------------+
| = 本文为Haohappy读<<Core PHP Programming>>
| = 中Classes and Objects一章的笔记
| = 翻译为主+个人心得
| = 为避免可能发生的不必要的麻烦请勿转载,谢谢
| = 欢迎批评指正,希望和所有PHP爱好者共同进步!
| = PHP5研究中心: http://blog.csdn.net/haohappy2004
+-------------------------------------------------------------------------------+
*/
第三节--定义一个类
当你声明一个类,你需要列出对象应有的所有变量和所有函数—被称为属性和方法. 3.1.1中显示了一个类的构成. 注意在大括号({})内你只能声明变量或者函数. 3.1.2中显示了如何在一个类中定义三个属性和两个方法.
3.1.1
class Name extends Another Class
{
Access Variable Declaration
Access Function Declaration
}
3.1.2
<?php
//定义一个跟踪用户的类
class User
{
//属性
public $name;
private $password, $lastLogin;
//方法
public function __construct($name, $password)
{
$this->name = $name;
$this->password = $password;
$this->lastLogin = time();
$this->accesses++;
}
// 获取最后访问的时间
function getLastLogin()
{
return(date("M d Y", $this->lastLogin));
}
}
//创建一个对象的实例
$user = new User("Leon", "sdf123");
//获取最后访问的时间
print($user->getLastLogin() ."<br>\n");
//打印用户名
print("$user->name<br>\n");
?>
【中国下载站】【设为主页】【收藏本页】【打印本文】【回到顶部】【关闭此页】