2010-01-15 141 views
1
<?php 
class abhi 
{ 
    var $contents="default_abhi"; 

    function abhi($contents) 
    { 
     $this->$contents = $contents; 
    } 

    function get_whats_there() 
    { 
     return $this->$contents; 
    } 

} 

$abhilash = new abhi("abhibutu"); 
echo $abhilash->get_whats_there(); 

?> 

我已經初始化變量內容的默認和構造函數,爲什麼值不打印,我應該在這裏糾正什麼?php代碼沒有執行?

看到錯誤,

[email protected]:~$ php5 pgm2.php 

Fatal error: Cannot access empty property in /home/abhilash/pgm2.php on line 13 
[email protected]:~$ 

回答

14

您錯誤地返回該變量的函數中。它應該是:

return $this->contents 
+0

什麼Extrakun意味着設置或獲取對象的變量時,你不包括$。 – 2010-01-15 14:19:23

+0

作業也是如此。 – falstro 2010-01-15 14:19:46

+2

實際上還存在另一個問題...... echo語句在abhilash變量名稱前需要一個美元符號。 – Narcissus 2010-01-15 14:26:50

4

如果我記錯這將是

 
$this->contents = $contents; 

 
$this->$contents = $contents; 
3

應該訪問和寫入被$ this->內容不是$這 - > $內容

0

使用$ this-> contents
我也是第一次有相同的公關Oblem

1

另外,你是否錯過了「echo abhilash-> get_whats_there();」的美元符號? ($ abhilash-> ..)

5

由於問題被標記爲「PHP 」這裏是你的類與php5 class notation一個例子(即公共/保護/私有的,而不是無功,公共/保護/私有函數, __construct()代替類名(),...)

class abhi { 
    protected $contents="default_abhi"; 

    public function __construct($contents) { 
    $this->contents = $contents; 
    } 

    public function get_whats_there() { 
    return $this->contents; 
    } 
} 

$abhilash = new abhi("abhibutu"); 
echo $abhilash->get_whats_there(); 
+0

+1我正要寫相同的...我太慢了。 – 2010-01-15 14:29:36

+0

是否有任何理由重新分配構造函數中的內容?我知道原來的海報有,但是它有價值嗎? – Tom 2010-01-15 14:40:22

+0

@Tom:你可以在運行時通過'$ a = new abhi('new content')設置內容' – 2010-01-15 15:08:54

0

你有$一個問題: 1.使用$這個 - 當>你不把$之間 「 - >」 和變量名「$」符號,所以你的$ this - > $內容應該是$ this-> contents。 2.在你的echo中,當從實例化的類中調用該函數時,你可以獲得$。

所以,你的正確的代碼是:

<?php 
class abhi 
{ 
    var $contents="default_abhi"; 

    function abhi($contents) 
    { 
     $this->contents = $contents; 
    } 

    function get_whats_there() 
    { 
     return $this->contents; 
    } 

} 

$abhilash = new abhi("abhibutu"); 
echo $abhilash->get_whats_there(); 

?>