2012-05-31 91 views
0

讓說:通過參數引用名稱獲取受保護的屬性?

class myclass{ 
    protected $info; 
    protected $owner; 
    __construct(){ 
     $this->info = 'nothing'; 
     $this->owner = 'nobody'; 
    } 
    function getProp($string){ 
     return $this->$string; 
    } 
} 

但它不是工作,是不是更多鈔票?它不返回任何東西或顯示錯誤

+0

適用於我(固定'_construct'聲明後,缺少'function'關鍵字)。 – webbiedave

回答

1

它工作正常,但是你錯過了在__construct前function關鍵字。這輸出「什麼都沒有」:

<?php 

class myclass{ 
    protected $info; 
    protected $owner; 

    function __construct(){ 
     $this->info = 'nothing'; 
     $this->owner = 'nobody'; 
    } 
    function getProp($string){ 
     return $this->$string; 
    } 
} 

$test = new myclass(); 
echo $test->getProp('info'); 
+0

不錯,幾乎確切 –

+0

哈哈耶,幾乎同時也是。有趣的是,我選擇在'__construct'周圍反引號,並選擇將它們放在'function'中。 – Paulpro

1

我你的__construct前要加上function,但除此之外,它似乎做工精細

class myclass{ 
    protected $info; 
    protected $owner; 
    function __construct(){ 
     $this->info = 'nothing'; 
     $this->owner = 'nobody'; 
    } 
    function getProp($string){ 
     return $this->$string; 
    } 
} 

$m = new myclass(); 
echo $m->getProp('info'); 

// echos 'nothing'