Why do I get this error when trying to set up a class variable
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'];
}
}
精彩评论