2012-11-26 56 views
1

parent屬性我有這樣兩類:如何設置從繼承

<?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

這是不工作? echo $ this-> x; –

+0

@HeXa只是它沒有穿過我的腦海。 – SIFE

回答

1

將在構造函數中你的任務,而只使用$this

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

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

在這裏看到它在行動:http://codepad.org/bbrGXFWP