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)); } }
类方法可能包含PHP中所谓的type hint. Type hint 是另一个传递参数给方法的类的名字. 如果你的脚本调用方法并传递一个不是类的实例的变量,PHP将产生一个”致命(fatal)错误” . 你可能没有给其它类型给出type hint,就像整型,字符串,或者布尔值. 在书写的时候, type hint是否应当包含数组类型仍存在争议.
Type hint是测试函数参数或者运算符的实例的数据类型的捷径. 你可能总是返回这个方法. 确认你强制让一个参数必须是哪种数据类型,如整型. 3.2.1 确保编译类只产生Widget的实例.
3.2.1
<?php //组件 class Widget { public $name='none'; public $created=FALSE; }
//装配器 class Assembler { public function make(Widget $w) { print("Making $w->name<br>n"); $w->created=TRUE; } }
//建立一个组件对象 $thing = new Widget; $thing->name = 'Gadget';