php 如何从对象(stdClass)中获取值?

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

How do I get the value from object(stdClass)?

phpparsing

提问by dwarbi

Using PHP, I have to parse a string coming to my code in a format like this:

使用 PHP,我必须以如下格式解析进入我的代码的字符串:

object(stdClass)(4) { 
    ["Title"]=> string(5) "Fruit" 
    ["Color"]=> string(6) "yellow" 
    ["Name"]=> string(6) "banana" 
    ["id"]=> int(3) 
}

I'm sure there's a simple solution, but I can't seem to find it... how to get the Color and Name?

我确定有一个简单的解决方案,但我似乎找不到它......如何获得颜色和名称?

Thanks so much.

非常感谢。

回答by Naftali aka Neal

You can do: $obj->Titleetcetera.

你可以这样做:$obj->Title等等。

Or you can turn it into an array:

或者你可以把它变成一个数组:

$array = get_object_vars($obj);

回答by dwarbi

You create StdClass objects and access methods from them like so:

您可以像这样创建 StdClass 对象并从中访问方法:

$obj = new StdClass;

$obj->foo = "bar";
echo $obj->foo;

I recommend subclassing StdClass or creating your own generic class so you can provide your own methods.

我建议继承 StdClass 或创建您自己的泛型类,以便您可以提供自己的方法。

Turning a StdClass object into an array:

将 StdClass 对象转换为数组:

You can do this using the following code:

您可以使用以下代码执行此操作:

$array = get_object_vars($obj);

Take a look at: http://php.net/manual/en/language.oop5.magic.phphttp://krisjordan.com/dynamic-properties-in-php-with-stdclass

看看:http: //php.net/manual/en/language.oop5.magic.php http://krisjordan.com/dynamic-properties-in-php-with-stdclass

回答by mfink

Example StdClass Object:

示例 StdClass 对象:

$obj = new stdClass();

$obj->foo = "bar";

By Property(as other's have mentioned)

按财产(正如其他人所提到的)

echo $obj->foo; // -> "bar"

By variable's value:

通过变量的值

$my_foo = 'foo';

echo $obj->{$my_foo}; // -> "bar"