2

嗨stackOverflow家庭:),

我有一个问题,我没有在其他地方找到答案。我试图解释我的问题:我有一个类,如果我从中创建另一个类,则从该子类我无法访问父类的属性。我做错事情了?我尝试将我的类变量复制到本地并尝试返回该本地变量,但以下 3 种方式均无效。

这是我的例子。起初我简单地创建一个对象:

$test = new test();

我的两个班级如下:

class test {

    public $testvar;

    public function __construct() {
        $this->testvar = 1234568;
        echo ":) ".$this->testvar();
        $test2 = new test2();
}

    public function testvar() {
        echo "testvar() called > ";
        return $this->testvar;
    }
}

和测试2:

class test2 extends test  {

    public function __construct() {
        echo "<br>:| this-> ".$this->testvar;
        echo "<br>:| parent:: ". parent::testvar();
        echo "<br>:| "; $this->testvar();
    }

}

有人可以有一个想法吗?谢谢

4

2 回答 2

6

你误解了继承的概念。test2在构造函数中实例化test不是继承。

的构造函数test没有被调用,因此testvar没有被设置。$test2 = new test2();从 的构造函数中删除test。尝试:

class test {

    public $testvar;

    public function __construct() {
        $this->testvar = 1234568;
        echo ":) ".$this->testvar();
}

    public function testvar() {
        echo "testvar() called > ";
        return $this->testvar;
    }
}

class test2 extends test  {

    public function __construct() {
        parent::__construct();
        echo "<br>:| this-> ".$this->testvar;
        echo "<br>:| "; $this->testvar();
    }

}

$test2 = new test2();

另请参阅有关构造函数(以及类)的PHP 手册

于 2011-07-23T10:48:49.097 回答
0

我想,如果您在 test 的构造函数中实例化 test2,这并不意味着 test 2 在您创建的上下文中实例化,这意味着:您设置的变量不可用于 test2 :)...我绝对不应该成为技术专家 :-D

test2 应该类似于:

class test2 extends test  {

public function __construct() {
    parent::__construct();
    echo "<br>:| this-> ".$this->testvar;
    echo "<br>:| parent:: ". parent::testvar();
    echo "<br>:| "; $this->testvar();
  }
}

和测试构造函数:

public function __construct() {
    $this->testvar = 1234568;
    echo ":) ".$this->testvar();
}

然后你在这些类之外调用 new test2() !

于 2011-07-23T10:54:35.827 回答