views:

21

answers:

2

I'm new to PHP 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.

+4  A: 

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";
    }
}
Yacoby
+1  A: 

You should assign your variable in a constructor

class someClass {

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

}
adam