有没有办法 "cast" 一个数组到(对象)作为 class/trait 的 属性?
Is there a way to "cast" an array to (object) as a property of class/trait?
在 PHP 中,我喜欢像这样一步声明对象(stdClass 的新实例)的能力:
$obj = (object) ['a','b','c'];
效果很好.. 但是作为class 属性:
class Foo {
public $obj = (object) ['a','b','c'];
}
我收到以下错误:
syntax error, unexpected '(object)' (object) (T_OBJECT_CAST)
还有其他方法可以实现吗?而且,有谁知道为什么不允许使用上述代码(可能特定于 php 5.6)?我在任何地方都找不到具体的文档。
引自PHP Docs:
They [object properties] 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.
(我的重点)
和
public $obj = (object) ['a','b','c'];
依赖于run-time
信息,即运行次数组到对象的转换
解决这个问题的方法是在构造函数中赋值
在 PHP 中,我喜欢像这样一步声明对象(stdClass 的新实例)的能力:
$obj = (object) ['a','b','c'];
效果很好.. 但是作为class 属性:
class Foo {
public $obj = (object) ['a','b','c'];
}
我收到以下错误:
syntax error, unexpected '(object)' (object) (T_OBJECT_CAST)
还有其他方法可以实现吗?而且,有谁知道为什么不允许使用上述代码(可能特定于 php 5.6)?我在任何地方都找不到具体的文档。
引自PHP Docs:
They [object properties] 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.
(我的重点)
和
public $obj = (object) ['a','b','c'];
依赖于run-time
信息,即运行次数组到对象的转换
解决这个问题的方法是在构造函数中赋值