所谓封装就是隐藏内部实现细节,提供外部访问方式
将一系列私有的特征保存起来
class Person { private $ID; public function setID($id) { $this->ID = ($id + 1)*3; } public function getID() { return $this->ID; } } $wang = new Person(); $wang->setID('123'); //我们不去关心id是如何生成的,我们只需要拿到我们想要的,这就是封装 print $wang->getID();接口自身也允许多继承,但是父子之间方法不能同名
<?php interface People { public function age(); } interface Human { public function name(); } interface Person extends Human,People { public function gender(); }
类与接口之间允许多继承
<?php interface A { public function a(); } interface B { public function b(); } /* * 可以同时实例化多个接口 解决单继承问题 */ class E implements A,B { const E1 = '15'; //类中常量使用 static $e2 = 1; //类中静态变量使用 public $e3 =2; //类中普通成员变量使用 public function __construct(){ self::$e2++; } public function a(){ echo 'E1:'.self::E1."\n"; } public function b(){ echo 'e1:'.self::$e2."\n"; } } $e1 = new E(); $e1->a(); $e1->b(); $e2 = new E(); $e1->a(); $e1->b(); $e2->a();<?php abstract class Animal { abstract public function say(); } class Cat extends Animal { public function say() { echo 'maio'; } } class Dog extends Animal { public function say() { echo 'wang'; } } function said($animal) { if($animal instanceof Animal){ $animal->say(); } } said(new Cat()); said(new Dog());
<?php class A { public $aa = 2; } $a1 = new A(); $a2 = $a1; $a3 = clone $a1; $a1->aa = 5; print $a2->aa,"\n"; print $a3->aa,"\n"; ?>
结果是 3 5 为什么不是 3和3,这里的$a2获得的只是$a1对象的句柄(id),并不是对象的完整拷贝,所以,如果要使用对象的完整拷贝,请使用clone,以免获得意想不到的结果。