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

Is there a special object initializer construct in PHP like there is now in C#?(PHP 中是否有像现在 C# 中那样的特殊对象初始化器构造?)
本文介绍了PHP 中是否有像现在 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.

推荐答案

从 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

这篇关于PHP 中是否有像现在 C# 中那样的特殊对象初始化器构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)