php面向对象特性小例
- 对象链原理
1 class Person 2 { 3 public function find(){ 4 echo 'find<br>'; 5 return $this; 6 } 7 public function attr(){ 8 echo 'attr<br>'; 9 return $this; 10 } 11 public function parent(){ 12 echo 'parent<br>'; 13 return $this; 14 } 15 public function css(){ 16 echo 'css'; 17 } 18 } 19 20 $obj = new Person(); 21 $obj->find()->attr()->parent()->css();
- 继承特性
1 class Person 2 { 3 public $name; 4 public $age; 5 6 function __construct($n,$a) 7 { 8 $this->name = $n; 9 $this->age = $a; 10 } 11 12 public function say(){ 13 echo "<p>my name is {$this->name},the age is {$this->age}</p>"; 14 } 15 } 16 17 class It extends Person 18 { 19 public $soft; 20 function __construct($n,$a,$s) 21 { 22 parent::__construct($n,$a); 23 $this->soft = $s; 24 } 25 26 public function soft(){ 27 echo "<p>{$this->name}正在开发{$this->soft}软件</p>"; 28 } 29 } 30 31 $obj = new It('yu',30,'PHP'); 32 $obj->say(); 33 $obj->soft();
- 封装特性
1 class Counter 2 { 3 private $n1; 4 private $n2; 5 public function __construct($n1,$n2) 6 { 7 $this->n1 = $n1; 8 $this->n2 = $n2; 9 } 10 11 private function getSum(){ 12 return $this->n1+$this->n2; 13 } 14 15 private function getProduct(){ 16 return $this->n1*$this->n2; 17 } 18 19 public function getReturn(){ 20 return $this->getProduct()-$this->getSum(); 21 } 22 } 23 24 $obj = new Counter(5,5); 25 echo $obj->getReturn();