新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

php如何调用父类构造方法?

php调用父类构造方法:使用parent调用父类的构造,用【::】引用一个类,代码为【parent::__construct($title,$firstName,$mainName,$price)】。

创新互联公司专注于涞水网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供涞水营销型网站建设,涞水网站制作、涞水网页设计、涞水网站官网定制、重庆小程序开发服务,打造涞水网络公司原创品牌,更为您提供涞水网站排名全网营销落地服务。

php调用父类构造方法:

使用parent调用父类的构造方法

要引用一个类而不是对象的方法,可以使用::(两个冒号),而不是->

所以,parent::__construct()为着调用父类的__construct()方法。

具体代码如下:

 title = $title;    // 给属性 title 赋传进来的值
$this -> producerFirstName= $firstName; 
$this -> producerMainName = $mainName; 
$this -> price= $price; 
}
function getProducer(){    // 声明方法
return "{$this -> producerFirstName }"."{$this -> producerMainName}";
}
function getSummaryLine(){
$base = "{$this->title}( {$this->producerMainName},";
$base .= "{$this->producerFirstName} )";
return $base;
}
}
class CdProduct extends ShopProduct {
public $playLenth;
function __construct($title,$firstName,$mainName,$price,$playLenth){
parent::__construct($title,$firstName,$mainName,$price);
$this -> playLenth= $playLenth;
}
function getPlayLength(){
return $this -> playLength;
}
function getSummaryLine(){
$base = "{$this->title}( {$this->producerMainName},";
$base .= "{$this->producerFirstName} )";
$base .= ":playing time - {$this->playLength} )";
return $base;
}
}
// 定义类
class BookProduct extends ShopProduct {
public $numPages;
function __construct($title,$firstName,$mainName,$price,$numPages){
parent::__construct($title,$firstName,$mainName,$price);
$this -> numPages= $numPages;
}
function getNumberOfPages(){
return $this -> numPages;
}
function getSummaryLine(){
$base = "{$this->title}( {$this->producerMainName},";
$base .= "{$this->producerFirstName} )";
$base .= ":page cont - {$this->numPages} )";
return $base;
}
}
 
?>

每个子类都会在设置自己的属性前调用父类的构造方法。基类(父类)现在仅知道自己的数据,而我们也应该尽量避免告诉父类任何关于子类的信息,这是一条经验规则,大家想想如果某个子类的信息应该是”保密“的,结果父类知道它的信息,其它子类可以继承,这样子类的信息就不保密了。


当前名称:php如何调用父类构造方法?
网站URL:http://www.wjwzjz.com/article/cpoeog.html
在线咨询
服务热线
服务热线:028-86922220
TOP