Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php构造函数继承_Php_Inheritance_Constructor - Fatal编程技术网

php构造函数继承

php构造函数继承,php,inheritance,constructor,Php,Inheritance,Constructor,我想澄清我遇到的一个问题 我有一个数据库基类,它将被一组其他类继承。构造函数如下所示: public function __construct ($table) { $this->table = $table; $this->db = new Database(); $this->db->connect(); } $pg = new planetsGames('uselessStringHereThatHasNoUtilityAtAll')

我想澄清我遇到的一个问题

我有一个数据库基类,它将被一组其他类继承。构造函数如下所示:

public function __construct ($table)
{
     $this->table = $table;
     $this->db = new Database();
     $this->db->connect();
}
$pg = new planetsGames('uselessStringHereThatHasNoUtilityAtAll');
我将从此构造函数从子项调用,如下所示:

 public function __construct ($something)
{
    parent::__construct("planets_games");
}
 Fatal error: Declaration of planetsGames::__construct() must be compatible with that of IScaffold::__construct()
我的问题是php不允许我在没有$something参数的情况下生成子构造函数 我得到以下信息:

 public function __construct ($something)
{
    parent::__construct("planets_games");
}
 Fatal error: Declaration of planetsGames::__construct() must be compatible with that of IScaffold::__construct()
我目前正在通过如下方式实例化对象来绕过此问题:

public function __construct ($table)
{
     $this->table = $table;
     $this->db = new Database();
     $this->db->connect();
}
$pg = new planetsGames('uselessStringHereThatHasNoUtilityAtAll');
我认为我在基本的php知识中遗漏了一些非常重要的东西


非常感谢您提前提供的帮助

此错误消息指的是。 它适用于每个IS-A关系(这是使用继承(extends)的含义),并声明每个子类型都应该完全可替换为超级类型

但这不适用于构造函数!您正在使用哪个php版本

基类似乎已将构造函数标记为抽象的。这是唯一的办法 可能会出现此错误

永远不要将构造函数标记为抽象、最终或将其放入接口中

在大多数语言中,这甚至是不可能的

你应该从中吸取的是,最好的做法是 每个具体对象都有一个构造函数,其签名最好 表示使用者应如何完全实例化该特定对象 对象在某些涉及继承的情况下,“借用” 父构造函数是可接受且有用的。此外,它是 鼓励您在对特定类型进行子类化时 适当时,类型应该有自己的构造函数来生成 对新的子类型最有意义


是的,php目前严格要求子类的构造参数必须与父类的构造参数兼容。还有什么是你得不到的?你不能做这样的事情,但你可以不与父母和孩子争论;然而,仅从子结构将参数传递给父结构。这是你想要的吗?很抱歉回复太晚。我使用的是版本5.3.13。LSP不是只有在我们讨论多态性时才适用吗?我最初的想法是一样的,但它是一个构造函数,不是一个常规方法。我们没有构造函数的合同,是吗?没有,但是在php中你可以将构造函数标记为抽象的。我认为在上面的例子中,在一个超级类(IScaffold?)中是这样的,否则致命的错误不会发生。使构造函数抽象会从LSP引入相同的约束。正如我上面所说,我认为这是一种不好的做法。