PHP 中是否有像现在 C# 中那样的特殊对象初始化器构造?

2022-01-19 00:00:00 oop initialization constructor php

我知道在 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.

推荐答案

从 PHP7 开始,我们有 匿名类 允许您在运行时扩展类,包括设置附加属性:

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

相关文章