时间:2021-07-01 10:21:17 帮助过:3人阅读
<?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)
重写,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,父类
一旦重写,父类代码就不会在执行了!
父类子类的同名方法就会出现重写,因此有些方法是一定会重写的比如构造方法!
<?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.gxlcms.com)!