![](/img/trans.png)
[英]How do you set the value of a parent class variable in an inherited class but then use it in an inherited function?
[英]How to set a parent property from inherited class
我有兩節課:
<?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中實現?
將您的分配放入構造函數中,然后使用$this
:
class TestEx extends Test
{
public function __construct()
{
$this->x = 7;
}
public function getX()
{
echo $this->x;
}
}
實際操作見這里: http : //codepad.org/bbrGXFWP
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.