我需要在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 } }
我知道这是一件奇怪的事情,我正在尝试找到一种闻起来并不难闻的方法,但是尽管如此,我很好奇。
丑陋的解决方法是将一个布尔参数传递给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); } }