像现在的C#中一样,PHP中是否有一个特殊的对象初始化构造器? [英] Is there a special object initializer construct in PHP like there is now in C#?
问题描述
我知道现在在C#中您可以做到:
I know that in C# you can nowadays do:
var a = new MyObject
{
Property1 = 1,
Property2 = 2
};
PHP也有类似的东西吗?还是我应该通过构造函数或通过多个语句来做到这一点?
Is there something like that in PHP too? Or should I just do it through a constructor or through multiple statements;
$a = new MyObject(1, 2);
$a = new MyObject();
$a->property1 = 1;
$a->property2 = 2;
如果有可能,但每个人都认为这是一个糟糕的主意,我也想知道.
If it is possible but everyone thinks it's a terrible idea, I would also like to know.
PS:对象不过是一堆属性而已.
PS: the object is nothing more than a bunch of properties.
推荐答案
As of PHP7, we have Anonymous Classes which would allow you to extend a class at runtime, including setting of additional properties:
$a = new class() extends MyObject {
public $property1 = 1;
public $property2 = 2;
};
echo $a->property1; // prints 1
在PHP7之前,没有这样的东西.如果您的想法是使用任意属性实例化对象,则可以
Before PHP7, there is no such thing. If the idea is to instantiate the object with arbitrary properties, you can do
public function __construct(array $properties)
{
foreach ($properties as $property => $value)
{
$this->$property = $value
}
}
$foo = new Foo(array('prop1' => 1, 'prop2' => 2));
根据需要添加变体.例如,将检查添加到property_exists
仅允许设置已定义的成员.我发现在对象上抛出随机属性是设计缺陷.
Add variations as you see fit. For instance, add checks to property_exists
to only allow setting of defined members. I find throwing random properties at objects a design flaw.
如果不需要特定的类实例,而只需要一个随机的对象包,也可以
If you do not need a specific class instance, but you just want a random object bag, you can also do
$a = (object) [
'property1' => 1,
'property2' => 2
];
这将为您提供StdClass的实例,并且您可以通过以下方式访问
which would then give you an instance of StdClass and which you could access as
echo $a->property1; // prints 1
这篇关于像现在的C#中一样,PHP中是否有一个特殊的对象初始化构造器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!