php面向对象语法3 继承extends

来源:互联网 发布:淘宝升钻后流量下降 编辑:程序博客网 时间:2024/05/28 05:14

继承:如果一个对象A,使用了另一个对象B的成员,那么我们就称A对象继承了B对象!
tip:继承概念体现在对象上,语法体现在类上 class B extends A { }!
此时,特定的称谓:
Goods:父类,基础类!Book:子类,扩展类!

<?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');

语法意义就是,面向对象语法中的,代码的重用!
作用:在很多类里能共享一段代码,即类之间的数据共享。
作用场景:
比如class Table1Model extends Model{} class Table2Model extends Model{}
如果没有用继承,那么对应不同表的不同Model类都得重写一段连接数据库的代码。
用继承,只需在基础Model类里写上连接数据库的方法,其他子类就能调用了。

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)
可见,如果一个对象是子类的实例,那么也是父类的实例。



重写,override。是个现象,只有继承会出现(利用或者避免这个情况)
如果子类,与父类,出现同名的成员(属性,方法),则在实例化子类对象时,只会得到子类中定义的成员,称之为重写!
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,父类
一旦重写,父类代码就不会在执行了!
父类子类的同名方法就会出现重写,因此有些方法是一定会重写的比如构造方法!
要想让Book的四个属性都有值,有两个办法
1 把父类构造函数的代码

$this->goods_name = $name;$this->goods_price = $price;

复制到子类构造函数之中

$this->goods_name = $name;$this->goods_price = $price;$this->author = $author;$this->publisher = $publisher;

2.在子类构造函数中用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)
}

0 0
原创粉丝点击