Listing 6.8 Private members
<?php class Widget { private $name; private $price; private $id;
public function __construct($name, $price) { $this->name = $name; $this->price = floatval($price); $this->id = uniqid(); } //checks if two widgets are the same 检查两个widget是否相同 public function equals($widget) { return(($this->name == $widget->name)AND ($this->price == $widget->price)); } } $w1 = new Widget('Cog', 5.00); $w2 = new Widget('Cog', 5.00); $w3 = new Widget('Gear', 7.00);
//TRUE if($w1->equals($w2)) { print("w1 and w2 are the same<br>n"); }
//FALSE if($w1->equals($w3)) { print("w1 and w3 are the same<br>n"); }
//FALSE, == includes id in comparison if($w1 == $w2) file://不等,因为ID不同 { print("w1 and w2 are the same<br>n"); } ?>
一个子类可能改变通过覆写父类方法来改变方法的访问方式,尽管如此,仍然有一些限制. 如果你覆写了一个public类成员,他子类中必须保持public. 如果你覆写了一个protected成员,它可保持protected或变成public.Private成员仍然只在当前类中可见. 声明一个与父类的private成员同名的成员将简单地在当前类中建立一个与原来不同的成员. 因此,在技术上你不能覆写一个private成员.