Is there a special object initializer construct in PHP like there is now in 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# 中那样的特殊对象初始化器构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP 中是否有像现在 C# 中那样的特殊对象初始化器构造?


基础教程推荐
- Libpuzzle 索引数百万张图片? 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在多维数组中查找最大值 2021-01-01