javascript PHP 内联写入对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13417092/
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-10-26 18:42:57  来源:igfitidea点击:

PHP write objects inline

phpjavascriptarraysobjectsyntax

提问by user1821218

Im starting to move away from using arrays in PHP as objects are so much neater and in php 5 there is no performance hits when using objects.

我开始不再在 PHP 中使用数组,因为对象非常整洁,而且在 php 5 中使用对象时没有性能下降。

Currently the way I do it is:

目前我的做法是:

$object = (object) array('this' => 'that', 'foo' => (object) array('bar' => 123));

$object = (object) array('this' => 'that', 'foo' => (object) array('bar' => 123));

However, i find it so tedious to have to typecast every time as typecasting isnt recursive...

但是,我发现每次都必须进行类型转换非常乏味,因为类型转换不是递归的......

Is there any way in php (or will there be) to do it like this or something similar:

在 php 中有没有办法(或者会有)像这样或类似的东西:

$object = {
    'this' => 'that',
    'foo' => {
        'bar' => 123
    }
};

回答by Ivan Yarych

Starting from PHP 5.4 short array syntax has become available. This allows you to initialize array like this:

从 PHP 5.4 开始,短数组语法变得可用。这允许您像这样初始化数组:

$myArray = ["propertyA" => 1, "propertyB" => 2];

There is no currently short object syntax in PHP as of PHP7. But you can cast short array syntax to create objects like this:

从 PHP7 开始,PHP 中目前没有简短的对象语法。但是您可以使用简短的数组语法来创建这样的对象:

$myObject = (object) ["propertyA" => 1, "propertyB" => 2];

Looks much nicer and shorter than using the following construct:

看起来比使用以下结构更好更短:

$myObject = new \StdClass();
$myObject->propertyA = 1;
$myObject->propertyB = 2;

回答by David Gassama

I recommend you to build a function width StdClass.

我建议您构建一个函数 width StdClass

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;
    }
}

回答by Jason McCreary

PHP does not currently support short object syntax. As of PHP 5.4 they support short array syntax. Maybe 5.5 will include what you are after.

PHP 目前不支持短对象语法。从 PHP 5.4 开始,它们支持短数组语法。也许 5.5 将包括您所追求的。

As an alternative:

作为备选:

You could craft your objects as JSON and use json_decode():

您可以将对象制作为 JSON 并使用json_decode()

$json = '{"this": "that", "foo": {"bar": 123}}';
var_dump(json_decode($json));

Note:I am only showing this as demonstration of a way to solve your question. I am not advocating such a practice.

注意:我只是将其展示为解决您的问题的方法的演示。我不提倡这种做法。

回答by santiago arizti

I have an alternative solution for when you receive an already built array. Say your array has n nested arrays so you have no chance of casting each one in a simple way. This would do the trick:

当您收到已构建的数组时,我有一个替代解决方案。假设您的数组有 n 个嵌套数组,因此您没有机会以简单的方式投射每个数组。这可以解决问题:

$object = json_decode(json_encode($unknownArray));

I would not use this in a large loop or something similar, as it is way slower than just sticking with the array sintax and live with it. Also, if an element of the array is a function or some other funny thing this would break that.

我不会在大循环或类似的东西中使用它,因为它比仅仅坚持使用数组 sintax 并忍受它要慢得多。此外,如果数组的元素是函数或其他一些有趣的东西,这会破坏它。

Example usage:

用法示例:

$unknownArray = array(
    'a' => '1',
    'b' => '2',
    'c' => '3',
    'd' => array(
        'x' => '7',
        'y' => '8',
        'z' => '9',
    ),
);
$object = json_decode(json_encode($unknownArray));
echo $object->d->x;

回答by complex857

Unfortunately there's no syntax creating stdClassinstances like that. But you could use the newkeyword and any of the spl classes (not much tidier i admit). If you want to optimize for keystrokes, you could write a little helper function like this:

不幸的是,没有语法创建这样的stdClass实例。但是您可以使用new关键字和任何 spl 类(我承认不是很整洁)。如果你想优化击键,你可以写一个像这样的小辅助函数:

function O($a){
    return new ArrayObject($a); // has -> and [] support too
}

and write

和写

$stuff = O(array('a' => 'tickle me elmo', 'b' => O(array('foo' => 'bar'))));

回答by Elias Van Ootegem

Though I honestly can't see why you'd want to do this (associative arrays are in essence data-only-objects) but if you insist:
Instead of casting every single array, on every single level to an object, you could use the following "trick/hack":

虽然老实说我不明白你为什么要这样做(关联数组本质上是仅数据对象)但如果​​你坚持:
而不是将每个数组,在每一层上都投射到一个对象,你可以使用以下“技巧/黑客”

$object = json_decode(
              json_encode(
                   array('some'=>array('multi'=>'Dimensional'),
                         'array'=>'that',
                         'you' => array('want' => 'to',
                                        'turn' => 'into'),
                         'an' => 'object')));

This converts all arrays into instances of the stdClass, which I believe is what you wanted.
Again, I have to say: PHP is notJavaScript, and objects are far more expensive (relatively speaking) in languages like PHP, then they are in JS. I'd strongly recommend you stick with using assoc arrays if you don't need an object.

这会将所有数组转换为 的实例stdClass,我相信这是您想要的。
再次,我不得不说:PHP不是JavaScript,对象在像 PHP 这样的语言中要贵得多(相对而言),然后它们在 JS 中。如果您不需要对象,我强烈建议您坚持使用 assoc 数组。

Like objects, arrays can be type-hinted: function foo (array $argument){}
If you really want to turn them into a particular instance of some class, why not change the constructor, to deal with an array:

像对象一样,数组可以是类型提示的function foo (array $argument){}
如果你真的想把它们变成某个类的特定实例,为什么不改变构造函数来处理数组:

class My_Object extends stdClass
{
    public function __construct(array $params = null)
    {
        if (!empty($params))
        {
            foreach ($params as $name => $value)
            {
                $this->{$name} = $value;//set everything
            }
        }
    }
}

And go on to add whatever methods you want to add to the lot

然后继续添加您想要添加到该批次的任何方法