简体   繁体   English

将变量传递给扩展的PHP类

[英]Pass variable to extended PHP class

I've been using OOP in PHP for a while now, but for some reason am having a total brain meltdown and can't work out what's going wrong here! 我已经在PHP中使用OOP已经有一段时间了,但由于某些原因,我的脑部完全崩溃了,无法解决这里出了什么问题!

I have a much more complex class, but wrote a simpler one to test it, and even this isn't working... 我有一个更复杂的类,但写了一个更简单的类来测试它,甚至这不起作用......

Can anyone tell me what I'm doing wrong? 谁能告诉我我做错了什么?

class test
{
    public $testvar;

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

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

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

All I'm trying to do is pass a variable from the parent class to the child class! 我要做的就是将一个变量从父类传递给子类! I swear in the past I've just used $this->varName to get $varName in the extension?? 我发誓过去我刚用$ this-> varName来获取扩展名中的$ varName

Thanks! 谢谢!

You have to call the constructor of the parent class from the constructor of the child class. 您必须从子类的构造函数中调用父类的构造函数。

Which means, in your case, that your test2 class will then become : 在您的情况下,这意味着您的test2类将成为:

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

For more informations, you can take a look at the page Constructors and Destructors of the manual, which states, about your question : 有关更多信息,您可以查看手册的页面构造函数和析构函数 ,其中说明了您的问题:

Note: Parent constructors are not called implicitly if the child class defines a constructor . 注意: 如果子类定义构造函数,则不会隐式调用父构造函数 In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. 为了运行父构造函数,需要在子构造函数中调用parent::__construct()


You can use $this->varName : this is not a problem ; 你可以使用$this->varName :这不是问题; consider this code : 考虑这段代码:

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

The output is : 输出是:

int 2

Which is the "default" value of $testvar . 这是$testvar的“默认”值。

This means the problem is not that you cannot access that property : the problem, here, is only that the constructor of the parent class has not been called. 这意味着问题不在于您无法访问该属性:此处的问题仅在于未调用父类的构造函数。

Your test2 class should call 你的test2类应该调用

parent::__construct()

in its constructor. 在它的构造函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM