繼承:如果一個物件A,使用了另一個物件B的成員,那麼我們就稱A物件繼承了B物件!
tip:繼承概念體現在物件上,語法體現在類別上 class B extends A { }!
<?php class Goods{ public $goodsName; public $price; public function sayName($goodsName){ $this->goodsName=$goodsName; echo $this->goodsName; } } class Books extends Goods{ public function sayPrice($price){ $this->price=$price; echo $this->price.'人民币'; } } $book1=new Books; $book1->sayName('php开发'); $book1->sayPrice('156.47');
語法意義就是,物件導向語法中的,程式碼的重複使用!
instanceof,是否為某一類實例.(Instanceof和+-*/的概念一致,是運算子)
<?php class AmParent{ } class AmChild extends AmParent{ } $amChild=new AmChild; var_dump( $amChild instanceof AmChild); var_dump( $amChild instanceof AmParent);
運算結果:
bool(true)
bool(true)
如果子類,與父類,出現同名的成員(屬性,方法),則在實例化子類對象時,只會得到子類中定義的成員,稱之為重寫!
tip:
重寫不是替換!
兩個不同的sayprice都存在。我們透過Book類別物件拿到目前看到的屬性或方法,類似向上就近查找的過程。
<?php class Goods{ public $goodsName; public $price; public function sayPrice($price){ $this->price=$price; echo $this->price.'没有货币单位'; } } class Books extends Goods{ public function sayPrice($price){ $this->price=$price; echo $this->price.'人民币'; } } //$good=new Goods; //$good->sayPrice('96.47'); echo '<hr/>'; $book1=new Books; $book1->sayPrice('156.47');
156.47人民幣
parent,父類
一旦重寫,父類程式碼就不會在執行了!父類別子類別的同名方法就會出現重寫,因此有些方法是一定會重寫的例如建構方法!
<?php class Goods { public $goods_name = 'ITCAST';//名字 public $goods_price;//商品价格 public function __construct($name, $price) { $this->goods_name = $name; $this->goods_price = $price; } } class Book extends Goods { public $author;//作者 public $publisher;//出版社 public function __construct($name, $price,$author,$publisher) { parent:: __construct($name, $price); $this->author = $author; $this->publisher = $publisher; } } $book1=new Book('phpphpphp',88.8,'new','Bejjing publisher'); var_dump($book1);
object(Book)#1 (4) { [“author”]=> string(3) “new” [“publisher”]=> string(17) “Bejjing publisher” [“goods_name”]=> string(9) “phpphpphp” [“goods_price”]=> float(88.8) }
以上就是php物件導向語法3 繼承extends的內容,更多相關內容請關注PHP中文網(www.php.cn)!