2010-03-22 37 views
0

我是新來的PHP,所以也許我在這裏可以俯瞰東西,但以下幾點:試圖建立一個類變量時,爲什麼我得到這個錯誤

class someClass { 

    var $id = $_GET['id']; 

    function sayHello() { 

     echo "Hello"; 

    } 

} 

提供了以下錯誤:

解析錯誤:語法錯誤,在C意想不到T_VARIABLE:\ XAMPP \ htdocs中\文件\上線13 classes.php

如果不是$ _GET [ '身份證']我設置變量$ ID爲一個字符串,一切都很好,但。

回答

4

您不能使用構造函數以這種方式向類成員分配除常量以外的任何內容。

the manual

declaration [of a property] may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

做的另一種方法是to use a constructor設定值:

class someClass { 

    var $id; 

    public function __construct(){ 
     $this->id = $_GET['id']; 
    } 

    function sayHello() { 
     echo "Hello"; 
    } 
} 
1

你應該在構造函數中指定的變量

class someClass { 

    function __construct() { 
     $this->id = $_GET['id']; 
    } 

} 
相關問題