我有这两个类:
<?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中实现这一点?
答案 0 :(得分:0)
将你的作业放在构造函数中,然后使用$this
:
class TestEx extends Test
{
public function __construct()
{
$this->x = 7;
}
public function getX()
{
echo $this->x;
}
}
在此处查看:[{3}}