1

私はこの2つのクラスを持っています:

<?php

class Test 
{
    protected $x = 0;

    public function setX($x)
    {
        $this->x = $x;
    }

    public function getX()
    {
        echo $this->x;
    }
}


class TestEx extends Test
{
    //parent::$this->x = 7; it gives this error: Parse error: syntax error, unexpected '$x' (T_VARIABLE), expecting function (T_FUNCTION) in test.php

    public function getX()
    {
        echo parent::$this->x;
    }

}



$call_textex = new TestEx();
$call_textex->getX();


?>

ここで、継承されたクラスから基本クラスの $x プロパティを設定します。PHP5でそれを達成する方法は?

4

1 に答える 1

0

割り当てをコンストラクターに入れ、次を使用します$this

class TestEx extends Test
{
    public function __construct()
    {
        $this->x = 7;
    }

    public function getX()
    {
        echo $this->x;
    }
}

ここで実際に見てください:http://codepad.org/bbrGXFWP

于 2012-11-26T02:35:56.303 に答える