php对象:属性对象与stdClass对象-哪一个更好?

php对象:属性对象与stdClass对象-哪一个更好?,php,properties,std,Php,Properties,Std,有时我使用\u get或stdClass将数组转换为对象。但我不能决定我应该坚持到底。我想知道哪一个更好更快,有什么想法吗 class property { public function __get($name) { return (isset($this->$name)) ? $this->$name : null; } } $object = new property(); $object = new stdClass(); 因此

有时我使用
\u get
stdClass
数组转换为对象。但我不能决定我应该坚持到底。我想知道哪一个更好更快,有什么想法吗

class property 
{

    public function __get($name)
    {
        return (isset($this->$name)) ? $this->$name : null;
    }
}

$object = new property();
$object = new stdClass();
因此,如果我使用
newproperty()
,我将有一个属性对象输出

property Object
(
....
)
stdClass Object
(
....
)
而如果我使用
new stdClass()
,我将有一个stdClass对象输出

property Object
(
....
)
stdClass Object
(
....
)
因此,我可以像这样获取对象数据
$item->title

编辑:

如何进行实际的数组到对象的转换

public function array_to_object($array = array(), $property_overloading = false)
    {

        # If $array is not an array, let's make it array with one value of former $array.
        if (!is_array($array)) return $array;

        # Use property overloading to handle inaccessible properties, if overloading is set to be true.
        # Else use std object.
        if($property_overloading === true) $object = new property();
            else $object = new stdClass();

        foreach($array as $key => $value)
        {
            $key = (string) $key ;
            $object->$key = is_array($value) ? self::array_to_object($value, $property_overloading) : $value;
        }

        return $object;
    }
如果您只是将“property”类用作哑数据容器,那么就使用stdClass甚至数组。

首先,像您这样的(几乎)空类定义几乎就像
stdClass
一样,因此使用这两个类都不会有任何重大问题

也就是说,与stdClass相比,您的“命名”类的一个优点是,您可以通过使用
\uu get
魔术方法来定义当访问不存在的属性时会发生什么

class property
{
   public function __get($name)
   {
       return null;
   }
}
以上是对原始
属性
类的简单重写;调用
\uu get()
时,您已经知道
$this->$name
未设置。虽然这不会引起注意,但当您尝试引用
$obj->bla->bla
$obj->bla
不存在时,这并不能防止出现致命错误

在访问不存在的属性时引发异常可能更有用:

class property
{
   public function __get($name)
   {
       throw new Exception("Property $name is not defined");
   }
}

这允许您的代码在异常变成致命的运行时错误之前捕获异常,从而完全停止脚本。

我不熟悉这种技术。您可以像使用stdClass对象一样使用您创建的属性对象?是的,您可以。但我不确定它是否比stdClass object好……您忘了提到如何进行实际的数组到对象的转换。使用自己的属性类或像我说的那样作为数据容器有什么好处吗?看看这里,基本上,您所做的就是在类中存储数据(这就是我所说的数据容器)。没有任何方法或任何应用于您的属性类的东西会使它比stdClass更好。op询问哪一个更好?