|
由浅入深学习动态网页制作PHP的编程与应用(10) print $ncart->owner; // print the cart owners name $ncart->add_item("10", 1); // (inherited functionality from cart)
函数中的变量 $this 意思是当前的对象。你需要使用 $this->something 的形式来存取所有当前对象的变量或函数。
类中的构造器是你建立某种类的新变量时自动被调用的函数。类中和类名一样的函数就是构造器。
class Auto_Cart extends Cart { function Auto_Cart() { $this->add_item("10", 1); } }
这里定义一个类 Auto_Cart ,它给 Cart类加了一个每次new操作时设置项目10进行变量初始化的构造器。构造器也可以有参数,这些参数是可选的,这种特点也使得其十分有用。
class Constructor_Cart { function Constructor_Cart($item = "10", $num = 1) { $this->add_item($item, $num); } } // Shop the same old boring stuff. $default_cart = new Constructor_Cart; // Shop for real... $different_cart = new Constructor_Cart("20", 17);
|