I didn't use PHP in a while, but I've tried something like this:
<?php
class Something {
public $x = 2 * 3; // (line 4)
}
This code triggers the following error:
[Wed Feb 13 17:43:56 2013] [error] [client 127.0.0.1] PHP Parse error: syntax error, unexpected '*', expecting ',' or ';' in /var/www/problem.php on line 4
The PHP documentation says
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.
So, according to the docs, my code should work. Is there something I'm missing here?
When declaring members of a class you can assign values to them but you can't do complex operations like math or function calls.
<?php
class Something {
public $x = 2 * 3; // (line 4)
}
can be:
<?php
class Something {
public $x = 6; // (line 4)
}
So in your case you'll want to initialize that value in your constructor instead.
<?php
class Something {
public $x;
public function __construct()
{
$this->x = 2 * 3;
}
}
If you actually read carefully the documentation you linked to in the examples it clearly says that this is not allowed:
class SimpleClass
{
// invalid property declarations:
// (some examples here)
public $var3 = 1+2;
}
This implies that multiplication won't work either.
So, according to the docs, my code should work.
nope
The docs clearly state: "it must be able to be evaluated at compile time and must not depend on run-time information"
2 * 3
is run-time evaluation.
public $x = 6;
should work.
Run-time evaluation 2 * 3
is not allowed.
As the DOCS say
This declaration 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.