2009-09-19 37 views
3

我一直在PHP中使用OOP一段时间,但由于某种原因,我的整个大脑崩溃并无法解决这里出了什么问题!将变量传递给扩展的PHP类

我有一个更复杂的类,而是写了一个简单的一个测试它,甚至这是不工作...

谁能告诉我什么,我做错了什么?

class test 
{ 
    public $testvar; 

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

class test2 extends test 
{ 
    function __construct() 
    { 
     echo $this->testvar; 
    } 
} 

$test = new test; 
$test2 = new test2; 

我想要做的就是将一个变量从父类传递给子类!我发誓过去我刚用$ this-> varName得到$ varName的扩展名?

谢谢!

回答

15

您必须从子类的构造函数中调用父类的构造函数。

这意味着,你的情况,你的test2类将随即成为:

class test2 extends test 
{ 
    function __construct() 
    { 
     parent::__construct(); 
     echo $this->testvar; 
    } 
} 

欲了解更多信息,你可以看看说明书,其中规定,关于你的问题的Constructors and Destructors页:

注:父构造函数不 隐式调用如果子类 定义构造函数。为了运行 父构造函数,需要在 子构造函数中调用 parent::__construct()


您可以使用$this->varName:这是没有问题的;考虑下面的代码:

class test { 
    public $testvar = 2; 
    function __construct() { 
     $this->testvar = 1; 
    } 
} 
class test2 extends test { 
    function __construct() { 
     var_dump($this->testvar); 
    } 
} 
$test2 = new test2; 

输出是:

int 2 

这是$testvar “默认” 值。

这意味着问题不在于您无法访问该属性:此处的问题仅在于父类的构造函数未被调用。

+0

+1了解更多详情。 :) – Amber 2009-09-19 21:20:24

+0

太棒了!这工作!谢谢! – Matt 2009-09-19 22:17:37

+0

@Matt:不客气:-) ;; @Dav:谢谢! – 2009-09-19 22:20:19

2

test2类应该调用

parent::__construct() 
在其构造

+0

谢谢!我希望我可以将此添加为接受的答案! – Matt 2009-09-19 22:18:19