I am using PHP 5.3 on Ubuntu. I want to share a pair of code snippets and want to know the reason of such contradiction in order to initialize associated array.
Case 1: A part of class
class ui_template extends ui\ui_component{
private $path = __DIR__."/templates";
private $properties_template = array('path' => __DIR__.'/templates', 'file' => 'mytemplate.php', 'engine' => 'php'); // Parse error: syntax error, unexpected '.', expecting ')'
private $properties_template = array('path' => $path, 'file' => 'mytemplate.php', 'engine' => 'php'); // Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION
Case 2: A part of simple script
$path = __DIR__ . "/templates";
$temp = new widget\ui_template('new_template');
$temp->extend_template(NULL, array('path' => __DIR__."/templates")); // works fine
$temp->extend_template(NULL, array('path' => $path)); // works fine
In the first case at line#3 that is strange to report an error on .
while defining path
, means concatenation is not allowed there. While in case 2 nothing such error.
In the first case at line#4 a variable is also not allowed to initialized path
You can't use computed values when declaring class properties. They must be constant (literal string, number, etc.). Docs:
They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. 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.
Only declarations are allowed when defining properties. You cannot use any operator (like the concatenation (not "contradictory"!)), or function there.