2010-11-10 39 views
1

我有下面的類和它不接受$ this關鍵字的方法。 有人可以GUID

<?php 
class test { 

    function __construct($x, $y, $z){ 

     $this->$x = $x; 


     $this->testFunction(); 





public static function testFunction(){ 



    print '<br> here it is:'.$this->$x.'--<br>'; 
} 



//======================================================================================================================== 
} 
?> 

它給了我這個錯誤

Fatal error: Using $this when not in object context 
+0

self :: $ x ..試試! – Stewie 2010-11-10 17:21:00

+1

也許不相關,但是在構造函數上的錯誤結束}錯字?如果不是,那需要關閉。 – 2010-11-10 17:21:28

+2

請重新格式化您的代碼,因爲它似乎缺少一個}。 @ Stewie,這是另一個錯誤,它並不真的造成致命的錯誤。 – Shoe 2010-11-10 17:21:44

回答

5

在靜態函數,你需要使用self

print '<br> here it is:'.self::$x.'--<br>'; 

$this是指一個對象實例,這不不存在於靜態上下文中。

這就是說,在靜態情況下,構造函數將永遠不會被調用,所以$x將永遠是空的。我不確定public static function是否真的是你想要的。

編輯:此外,正如@netcoder指出的那樣,$x也需要聲明爲靜態成員。

+0

$ x需要被聲明爲靜態成員,否則當引用'self :: $ x'時會觸發致命錯誤。 – netcoder 2010-11-10 17:23:59

+0

@netcoder我不這麼認爲。因爲當? – 2010-11-10 17:25:21

+0

因爲只要我還記得。 – netcoder 2010-11-10 17:26:34

2

你的方法是靜態的,你不能在靜態環境中使用$此。您必須使用self,但它會觸發致命錯誤,因爲$ x未聲明爲靜態成員。

這將工作:

class test { 

    static protected $x = 'hello world'; 

    static public function testFunction() { 
     echo self::$x; 
    } 

} 
0

基本上你正在使用的關鍵字$這個類外。 這裏有很多語法錯誤:

1 - a }可能在第一個函數中丟失。 2 - 我認爲沒有使用的publicprotected,在類的函數聲明private關鍵字是錯誤的。 3 - 要叫你不得不使用$this->var_name語法一個變量,而採用恆定,你應該使用self::cons_name

+0

爲什麼從來不?使用'$''後::'是訪問靜態屬性的必需項,並且使用'$ this - > $ x'對於動態訪問對象屬性非常有用 – netcoder 2010-11-10 17:30:19

+0

True,正在編輯... – Shoe 2010-11-10 17:32:23

相關問題