PHP 之高级OOP特性
1.对象克隆
1 <?php 2 header("Content-type:text/html; charset=utf-8"); 3 4 #在对象前面加关键字clone来克隆对象 5 class Animal{ 6 private $age; 7 private $sex; 8 9 #为age定义一个设置方法与一个获取方法 10 function setAge($age){ 11 $this->age = $age; 12 } 13 14 function getAge(){ 15 return $this->age; 16 } 17 18 } 19 20 #创建新的Animal对象 21 $dog1 = new Animal(); 22 $dog1->setAge("23"); 23 24 $dog2 = clone $dog1; 25 $dog2->setAge("45"); 26 27 printf("dog1 age:%d <br>",$dog1->getAge()); 28 printf("dog2 age:%d <br>",$dog2->getAge()); 29 30 /* 输出 31 dog1 age:23 32 dog2 age:45 */
2.继承与接口
<?php header("Content-type:text/html; charset=utf-8"); #接口中所有方法必须实现,倘若实现类没有实现所有方法,则必须声明为抽象类 interface IPillage{ function emptyBankAccount(); function burnDocuments(); } #父类 class Employee{ private $name; #构造函数 function __construct($name){ $this->setName($name); } function setName($name){ if($name == "") echo "Name cannot be blank!"; else $this->name = $name; } function getName(){ return "My name is ".$this->name."<br>"; } } class Executive extends Employee implements IPillage{ #定义一个特有的方法 function pillageCompany(){ echo "i'am selling company !"; } #接口实现 function emptyBankAccount(){ echo "hello"; } function burnDocuments(){ echo "world"; } } class CEO extends Executive{ function __construct($name){ #当遇到parent::__construct()时,PHP开始沿着父类向上搜索合适的构造函数 parent::__construct($name); echo "<p>CEO object creat!</p>"; #显示引用构造函数 #Employee::__construct($name); } function getFacelift(){ echo "nip nip tuck tuck"; } } /* $exec = new Executive(); $exec->setName("Lily"); echo $exec->getName(); echo $exec->pillageCompany(); 输出: My name is Lily i'am selling company !*/ /* $ceo = new CEO(); $ceo->setName("Jack"); $ceo->pillageCompany(); $ceo->getFacelift();*/ #子类实例化时会执行父类构造函数 $ceo = new CEO("Dennis"); echo $ceo->getName();
3.抽象类
(1)抽象类是不能被实例化的类,只能由其他基类继承
(2)抽象类中定义的所有方法必须在子类中实现