【发布时间】:2016-02-13 10:32:29
【问题描述】:
大家好,我对 php 中的面向对象编程非常陌生。所以有时我在 PHP 中学习 OOP 时需要帮助。 这是一个名为 parentClass 的类,我有一些方法和属性,例如:
class parentClass
{
public $fname;
public $lname;
public $age;
function __construct($title, $firstName, $lastName, $age,$address)
{
$this->title = $title;
$this->fname = $firstName;
$this->lname = $lastName;
$this->age = $age;
$this->address = $address;
}
public function getFullName()
{
return $this->fname . " " . $this->lname. " ". $this->address;
}
}
我还有一个名为 childClass 的子类,它用几个其他属性和方法扩展了 parentClass,并且其中还有另一个 _constructor 函数。然后我用 parent::__construct 调用了 parentClass 的方法和属性
class childClass extends parentClass
{
function __construct($title1, $firstName1, $mainName1, $age1)
{
parent::__construct($title, $firstName, $lastName, $age, $address)
$this->title1 = $title1;
$this->fname1 = $firstName1;
$this->lname1 = $mainName1;
$this->age1 = $age1;
}
function getFullName1()
{
return $this->fname1 . " " . $this->lname1 . " ". $this->address;
}
}
所以现在我必须将参数传递给 parentClass 的 contrucotr 函数的参数。我希望 getFullName1 方法返回带有地址的数据。 如果我写:
$obj = new childClass("title", "Rohim", "Uddin", 50);
这里我只能在 childClass 的 __constructor 函数参数中传递参数。
我的问题是在哪里传递 parentClass 的 contrucotr 函数参数的参数?更具体的 $address 参数; 提前致谢。对于任何错误,我深表歉意。
【问题讨论】:
-
您不需要创建子构造函数。然后会自动调用父构造函数,参数相同。
-
但是我的子构造函数的参数与父构造函数的参数不同,我需要它们与我的子类的方法一起使用。 @Amarnasan
-
那你必须给参数
$address补一个值,和子类参数一起用parent::__construct($title, $firstName, $lastName, $age, 'anyAddress')调用父类