135-1821-9792

如何在php中调用父类构造方法-创新互联

创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!

创新互联公司服务项目包括瑞昌网站建设、瑞昌网站制作、瑞昌网页制作以及瑞昌网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,瑞昌网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到瑞昌省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!

这篇文章将为大家详细讲解有关如何在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中调用父类构造方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


文章题目:如何在php中调用父类构造方法-创新互联
文章起源:http://kswsj.com/article/dceihc.html

其他资讯



Copyright © 2009-2022 www.kswsj.com 成都快上网科技有限公司 版权所有 蜀ICP备19037934号