2009-12-25 11 views
10

可以说我有一个抽象的ParentClass和一个ChildClass。 ChildClass扩展了ParentClass。现在ParentClass已经有了这个漂亮的构造函数:子类是否也可以继承父类的构造函数,还是每个类都有自己的构造函数?

function __construct($tplFile) { 
    $this->$tplFile = $tplFile; 
} 

ChildClass会自动继承这个吗?如果我不向ChildClass添加任何构造函数,我是否可以说$foo = new ChildClass("foo.tpl.php");,以便调用ParentClass的构造函数?

回答

11

ChildClass会自动继承构造函数。

0

这两个问题的答案是

18

从PHP手册:

注意:如果孩子 类定义构造函数构造家长不隐式调用。为了运行父构造函数,需要在子构造函数中调用parent :: __ construct()的 为 。

+1

谢谢 - 这个答案对我很有帮助。 – 2010-05-12 19:43:51

+0

注意:调用parent :: __ construct()不会重定向参数。使用此: if(func_num_args()> 0) { \t $ constructorArgs = func_get_args(); (数组($ this,'parent :: __ construct'),$ constructorArgs);这个数组是一个数组, } else { \t parent :: __ construct(); } – StanE 2014-08-09 23:41:09

相关问题