[英]Pass arguments to parent class constructor in PHP?
I have 2 classes where parent is inherited by child. 我有2个类,其中父级由孩子继承。
class parentClass
{
private $table_name='';
public function __construct($argument)
{
$this->table_name=$argument;
echo $this->table_name;
}
}
class child extends parentClass
{
private $table="student";
public function __construct()
{
parent::__construct($this->table);
}
}
There is some thing like this below that has to be used but I am unable to understand how and why. 下面有一些类似的东西必须使用,但我无法理解如何以及为什么。
$args = func_get_args();
call_user_func_array(array($this, 'parent::__construct'), $args);
Help me as 帮帮我
What should be the correct code to achieve the correct logic and please support it with a reference to gain a better understanding.
什么是实现正确逻辑的正确代码,请提供参考以更好地理解。
Not a direct answer, but if I read the code correctly, you don't really want to pass a variable / value to the constructor. 这不是一个直接的答案,但是如果我正确地阅读了代码,则您实际上并不想将变量/值传递给构造函数。 Instead you want to pass a fixed class property like a table name.
相反,您想传递一个固定的类属性,例如表名。
In that case you could use a constant in the child class and set that in the parent's constructor. 在这种情况下,您可以在子类中使用一个常量,并在父类的构造函数中进行设置。 The child class would not need a separate constructor if that is all you want to do.
如果您想要做的只是子类,则不需要单独的构造函数。
So something like : 所以像 :
class parentClass
{
private $table_name;
function __construct() {
$this->table_name = static::TABLE;
echo $this->table_name;
}
}
class childClass extends parentClass
{
const TABLE = "student";
}
$obj = new childClass();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.