开发者

Class inheritance problem in PHP

Hi stackOverflow Family :),

I have a question, and I didt find the answer elsewhere. I try to explain my problem: I have a class, and if I create an other class from it, from that child class I couldnt access the parent's properties. I did something wrong? I tried to copy my class variable to a local and try to give back that local one, but neither works of the following 3 way.

Here is my examples. At first I simple create an object:

$test = new test();

And my two class is the following:

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;
    }
}开发者_开发百科

And test2:

class test2 extends test  {

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

}

May somebody have an idea? Thx


You've misunderstood the inheritance concept. Instantiating test2 in the constructor function of test is not inheritance.

The constructor of test was not called, therefore testvar was not set. Remove $test2 = new test2(); from the constructor of test. Try:

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();

See also the PHP manual on constructors (and classes too).


I guess, if you instanciate test2 in the constructor of test, it doesn't mean, that test 2 is instanciated in the context you've created, which means: the variables you set aren't available to test2 :)... I definetly shouldn't become a techear :-D

test2 should look something like:

class test2 extends test  {

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

and the test-constructor:

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

and then you call new test2() outside of those classes!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜