PHP中array()语法的矛盾行为


A contradictory behaviour of array() syntax in PHP

我在Ubuntu上使用PHP 5.3。我想分享一对代码片段,并想知道这种矛盾的原因,以便初始化相关的数组。

案例1:类

的一部分
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

案例2:部分简单脚本

$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
  • 在第一行#3中,在定义path时报告.错误是奇怪的,这意味着不允许在那里连接。

  • 在第一行#4的第一种情况下,变量也不允许初始化path

在声明类属性时不能使用计算值。它们必须是常量(字符串、数字等)。文档:

通过使用关键字public、protected或之一来定义它们私有的,后跟一个普通的变量声明。这个声明可以包含一个初始化,但是这个初始化必须是常数值——也就是说,它必须能够在编译时求值时间和必须不依赖于运行时信息,以便评估。

在定义属性时只允许声明。

不能使用任何运算符(比如串联(不是"矛盾"!))或函数。