开发者

Why do I get this error when trying to set up a class variable

开发者 https://www.devze.com 2022-12-23 15:34 出处:网络
I\'m new to PH开发者_高级运维P so maybe I am overlooking something here but the following: class someClass {

I'm new to PH开发者_高级运维P so maybe I am overlooking something here but the following:

class someClass {

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

    function sayHello() {

        echo "Hello";

    }

}

gives the following error:

Parse error: syntax error, unexpected T_VARIABLE in C:\xampp\htdocs\files\classes.php on line 13

If instead of $_GET['id'] I set the variable $id to a string, everything is fine though.


You cannot assign anything except constants to a class member in that way without using a constructor.

See 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.

The alternative method of doing it is to use a constructor to set the value:

class someClass {

    var $id;

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

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


You should assign your variable in a constructor

class someClass {

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

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号