批改状态:合格
老师批语:这种访问 限制, 与变量的作用域的功能是一样的, 就是变量的可见性或可用性, 别想太复杂了
一、父类中被声明为public或protected的属性可以被子类继承,而且在子类中的修改会影响到父类,父类中的修改也同样会影响子类。
二、父类中声明为private的属性不会被继承,父类构造函数中的语句$this->mShopName = "myShop";只是为子类中的属性mShopName赋值,与父类的属性mShopName没有任何关系,仅仅只是名字相同。因而在子类中的修改并不会影响到父类。
三、在子类覆盖父类的方法时要注意,在子类中重写的方法的访问权限一定不能低于父类被覆盖的方法的访问权限。例如父类中的方法的访问权限是protected,那么在子类中重写的方法的权限就要是protected或public。如果父类的方法是public权限,子类中要重写的方法只能是public。总之在子类中重写父类的方法时,一定要高于父类被覆盖的方法的权限。
四、可以通过两种方法实现在子类的方法中调用父类被覆盖的方法:
1、使用父类的 “类名::” 来调用父类中被覆盖的方法;
2、使用 “parent::” 的方试来调用父类中被覆盖的方法;
五、实例
<?php
/**
* ShopProduct类,父类
*/
class ShopProduct{
private $mShopName;
public $mTitle;
public $mPrice;
public function __construct ($shopName="shopName", $title="shopProduct" ,$price=0)
{
$this->mShopName = $shopName;
$this->mTitle = $title;
$this->mPrice = $price;
}
public function getShopName ()
{
return $this->mShopName;
}
public function getTitle ()
{
return $this->mTitle;
}
public function getPrice ()
{
return $this->mPrice;
}
}
/**
* BookProduct类,ShopProduct类的子类
*/
class BookProduct extends ShopProduct{
private $mAuthor;
public function __construct($title="", $author=".",$price=20)
{
parent::__construct("shopName","shopProduct", 10);
$this->mAuthor = $author;
$this->mTitle = $title; //覆盖父类中的mTitle属性
//$this->mPrice = 30; //未设置,会继承自ShopProduct类
$this->mShopName = "myShop";
}
public function getAuthor ()
{
return $this->mAuthor;
}
public function printBookInfo ()
{
/** 打印子类的属性值 */
print "author : ".$this->mAuthor.", title : ".$this->mTitle;
print ", price : ".$this->mPrice.", shopName : ";
print $this->mShopName."<br>"; //Undefined
/** 父类中的属性值 */
print "title: ".parent::getTitle().", price : ".parent::getPrice();
print ", shopName : ".parent::getShopName()."<br>";
}
}
$book = new BookProduct("hello","...",20);
$book->printBookInfo();点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号