我需要让PHP中的一个类构造函数调用其父对象的父对象的(祖父母?)构造函数,而不调用父构造函数。
// main class that everything inherits
class Grandpa
{
public function __construct()
{
}
}
class Papa extends Grandpa
{
public function __construct()
{
// call Grandpa's constructor
parent::__construct();
}
}
class Kiddo extends Papa
{
public function __construct()
{
// THIS IS WHERE I NEED TO CALL GRANDPA'S
// CONSTRUCTOR AND NOT PAPA'S
}
}
我知道这是一件奇怪的事情,我正在尝试找到一种不那么难闻的方法,但尽管如此,我还是很好奇这是否可能。
发布于 2009-10-13 00:28:01
丑陋的变通办法是向Papa传递一个布尔参数,表明您不希望解析它的构造函数中包含的代码。即:
// main class that everything inherits
class Grandpa
{
public function __construct()
{
}
}
class Papa extends Grandpa
{
public function __construct($bypass = false)
{
// only perform actions inside if not bypassing
if (!$bypass) {
}
// call Grandpa's constructor
parent::__construct();
}
}
class Kiddo extends Papa
{
public function __construct()
{
$bypassPapa = true;
parent::__construct($bypassPapa);
}
}
发布于 2009-10-13 00:18:00
您必须使用Grandpa::__construct()
,没有其他快捷方式可以使用它。此外,这还会破坏Papa
类的封装-当读取或处理Papa
时,可以安全地假定__construct()
方法将在构造期间被调用,但Kiddo
类不会这样做。
发布于 2012-01-18 19:51:07
class Grandpa
{
public function __construct()
{}
}
class Papa extends Grandpa
{
public function __construct()
{
//call Grandpa's constructor
parent::__construct();
}
}
class Kiddo extends Papa
{
public function __construct()
{
//this is not a bug, it works that way in php
Grandpa::__construct();
}
}
https://stackoverflow.com/questions/1557608
复制相似问题