要访问特定字段方法(例如使其为必填项),我使用$form->fields()['fieldname'],在本地主机上使用wamp可以正常工作,但在服务器上会抛出此错误:
Parse error: syntax error, unexpected '[' in (...)
我的服务器上安装的是PHP 5.3,因为我重新安装了WAMP并忘记将其更改回5.3,所以WAMP运行的是PHP 5.4。所以我想这就是错误的原因。
如何使用PHP 5.3通过数组键访问返回数组的对象方法?
Parse error: syntax error, unexpected '[' in (...)
我的服务器上安装的是PHP 5.3,因为我重新安装了WAMP并忘记将其更改回5.3,所以WAMP运行的是PHP 5.4。所以我想这就是错误的原因。
如何使用PHP 5.3通过数组键访问返回数组的对象方法?
从PHP 5.4开始,可以进行数组解引用,而在5.3版本中不行。
PHP.net:
从PHP 5.4开始,可以直接对函数或方法调用的结果进行数组解引用。之前只能使用临时变量。
正如问题所描述的那样,数组解引用是 PHP 5.4 中新增的特性,PHP 5.3 不支持此功能。
echo $form->fields()['fieldname']
这段代码可以在PHP 5.4及更高版本中运行。
如果要在PHP 5.3中运行,您需要执行以下操作之一:
Use a temporary variable:
$temp = $form->fields()
echo $temp['fieldname'];
Output the fields array as an object property rather than from a method:
ie this....
echo $form->fields['fieldname']
...is perfectly valid.
Or, of course, you could upgrade your server to PHP 5.4. Bear in mind that 5.3 will be declared end-of-life relatively soon, now that 5.5 has been released, so you'll be wanting to upgrade sooner or later anyway; maybe this is your cue to do? (and don't worry about it; the upgrade path from 5.3 to 5.4 is pretty easy; there's nothing really that will break, except things that were deprecated anyway)
如上所述,数组解引用仅适用于5.4或更高版本。但是,您可以保存对象,稍后访问字段:
$fields=$form->fields();
$value=$fields['fieldname']
...
$fields = $form->fields; echo $fields['fieldname'];
- Jon