问题描述
我需要在PHP中调用父类的父类(grandparent?)构造函数而不调用父构造函数的类构造函数。
I need to have a class constructor in PHP call its parent's parent's (grandparent?) constructor without calling the parent constructor.
// 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
}
}
$ b b
我知道这是一个奇怪的事情,我试图找到一种没有臭味的方法,但是我很好奇,如果可能的话。
I know this is a bizarre thing to do and I'm attempting to find a means that doesn't smell bad but nonetheless, I'm curious if it's possible.
EDIT
我以为我应该公布所选答案的理由。原因是;它最优雅的解决方案想要调用祖父母的构造函数,同时保留所有的值。这当然不是最好的方法,也不是OOP友好的,但这不是问题是问。
I thought I should post the rationale for the chosen answer. The reason being; it most elegant solutionto the problem of wanting to call the "grandparent's" constructor while retaining all the values. It's certainly not the best approach nor is it OOP friendly, but that's not what the question was asking.
对于以后遇到这个问题的任何人 - 请找到另一个解决方案。我能够找到一个更好的方法,不会对类结构造成严重破坏。所以应该你。
For anyone coming across this question at a later date - Please find another solution. I was able to find a much better approach that didn't wreak havoc on the class structure. So should you.
推荐答案
丑陋的解决方法是传递一个布尔参数到爸爸表明你不想解析代码包含在它的构造函数中。即:
The ugly workaround would be to pass a boolean param to Papa indicating that you do not wish to parse the code contained in it's constructor. i.e:
// 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);
}
}
这篇关于我如何获得一个PHP类构造函数来调用其父的父构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!