在 PHP 中初始化像数组这样的对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1738865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:40:33  来源:igfitidea点击:

Initialize Objects like arrays in PHP?

php

提问by Pekka

In PHP, you can initialize arrays with values quickly using the following notation:

在 PHP 中,您可以使用以下符号快速用值初始化数组:

$array = array("name" => "member 1", array("name" => "member 1.1") ) ....

is there any way to do this for STDClass objects? I don't know any shorter way than the dreary

有没有办法为 STDClass 对象做到这一点?我不知道比沉闷更短的路

$object = new STDClass();
$object->member1 = "hello, I'm 1";
$object->member1->member1 = "hello, I'm 1.1";
$object->member2 = "hello, I'm 2";

采纳答案by Tim Lytle

From a (now dead) post showing both type casting and using a recursive function to convert single and multi-dimensional arrays to a standard object:

来自(现在已死)的帖子,该帖子显示了类型转换和使用递归函数将单维和多维数组转换为标准对象:

<?php
function arrayToObject($array) {
    if (!is_array($array)) {
        return $array;
    }

    $object = new stdClass();
    if (is_array($array) && count($array) > 0) {
        foreach ($array as $name=>$value) {
            $name = strtolower(trim($name));
            if (!empty($name)) {
                $object->$name = arrayToObject($value);
            }
        }
        return $object;
    }
    else {
        return FALSE;
    }
}

Essentially you construct a function that accepts an $arrayand iterates over all its keys and values. It assigns the values to class properties using the keys.

本质上,您构造了一个接受 an$array并迭代其所有键和值的函数。它使用键将值分配给类属性。

If a value is an array, you call the function again (recursively), and assign its output as the value.

如果值是数组,则再次(递归地)调用该函数,并将其输出分配为该值。

The example function above does exactly that; however, the logic is probably ordered a bit differently than you'd naturally think about the process.

上面的示例函数正是这样做的;但是,逻辑的顺序可能与您自然想到的过程略有不同。

回答by Gumbo

You can use type casting:

您可以使用类型转换:

$object = (object) array("name" => "member 1", array("name" => "member 1.1") );

回答by nickl-

I also up-voted Gumbo as the preferred solution but what he suggested is not exactly what was asked, which may lead to some confusion as to why member1olooks more like a member1a.

我还投票支持 Gumbo 作为首选解决方案,但他的建议并不完全符合要求,这可能会导致对为什么member1o看起来更像member1a.

To ensure this is clear now, the two ways (now 3 ways since 5.4) to produce the same stdClassin php.

为了确保现在很清楚,在 php.ini 中产生相同的两种方式(从 5.4 开始现在是 3 种方式)stdClass

  1. As per the question's long or manual approach:

    $object = new stdClass;
    $object->member1 = "hello, I'm 1";
    $object->member1o = new stdClass;
    $object->member1o->member1 = "hello, I'm 1o.1";
    $object->member2 = "hello, I'm 2";
    
  2. The shorter or single line version (expanded here for clarity) to cast an object from an array, ala Gumbo's suggestion.

    $object = (object)array(
         'member1' => "hello, I'm 1",
         'member1o' => (object)array(
             'member1' => "hello, I'm 1o.1",
         ),
         'member2' => "hello, I'm 2",
    );
    
  3. PHP 5.4+ Shortened array declaration style

    $object = (object)[
         'member1' => "hello, I'm 1",
         'member1o' => (object)['member1' => "hello, I'm 1o.1"],
         'member2' => "hello, I'm 2",
    ];
    
  1. 根据问题的长或手动方法:

    $object = new stdClass;
    $object->member1 = "hello, I'm 1";
    $object->member1o = new stdClass;
    $object->member1o->member1 = "hello, I'm 1o.1";
    $object->member2 = "hello, I'm 2";
    
  2. 从数组中投射对象的较短或单行版本(为了清晰起见在此处进行了扩展),ala Gumbo 的建议。

    $object = (object)array(
         'member1' => "hello, I'm 1",
         'member1o' => (object)array(
             'member1' => "hello, I'm 1o.1",
         ),
         'member2' => "hello, I'm 2",
    );
    
  3. PHP 5.4+ 缩短的数组声明样式

    $object = (object)[
         'member1' => "hello, I'm 1",
         'member1o' => (object)['member1' => "hello, I'm 1o.1"],
         'member2' => "hello, I'm 2",
    ];
    

Will both produce exactly the same result:

两者都会产生完全相同的结果:

stdClass Object
(
    [member1] => hello, I'm 1
    [member1o] => stdClass Object
        (
            [member1] => hello, I'm 1o.1
        )

    [member2] => hello, I'm 2
)

nJoy!

快乐!

回答by Sparkup

You can use :

您可以使用 :

$object = (object)[]; // shorter version of (object)array();

$object->foo = 'bar';

回答by outis

You could try:

你可以试试:

function initStdClass($thing) {
    if (is_array($thing)) {
      return (object) array_map(__FUNCTION__, $thing);
    }
    return $thing;
}

回答by gnud

I use a class I name Dict:

我使用一个我命名为 Dict 的类:

class Dict {

    public function __construct($values = array()) {
        foreach($values as $k => $v) {
            $this->{$k} = $v;
        }
    }
}

It also has functions for merging with other objects and arrays, but that's kinda out of the scope of this question.

它还具有与其他对象和数组合并的功能,但这有点超出了这个问题的范围。

回答by Matthijs Wessels

from thisanswer to a similar question:

thisanswer to a similar question:

As of PHP7, we have Anonymous Classeswhich would allow you to extend a class at runtime, including setting of additional properties:

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

$a = new class() extends MyObject {
    public $property1 = 1;
    public $property2 = 2;
};

echo $a->property1; // prints 1

It's not as succinct as the initializer for array. Not sure if I'd use it. But it isanother option you can consider.

它不像数组的初始化程序那么简洁。不确定我是否会使用它。但这您可以考虑的另一种选择。

回答by Klesun

Another option for deepconversion is to use json_encode+ json_decode(it decodes to stdClass by default). This way you won't have to repeat (object)cast in each nested object.

深度转换的另一个选择是使用json_encode+ json_decode(默认情况下它解码为 stdClass)。这样您就不必(object)在每个嵌套对象中重复转换。

$object = json_decode(json_encode(array(
     'member1' => "hello, I'm 1",
     'member1o' => array(
         'member1' => "hello, I'm 1o.1",
     ),
     'member2' => "hello, I'm 2",
)));

output:

输出:

php > print_r($object);
stdClass Object
(
    [member1] => hello, I'm 1
    [member1o] => stdClass Object
        (
            [member1] => hello, I'm 1o.1
        )

    [member2] => hello, I'm 2
)