gpt4 book ai didi

PHP 对象 : property Object Vs stdClass Object - which one is better?

转载 作者:搜寻专家 更新时间:2023-10-31 21:13:51 25 4
gpt4 key购买 nike

有时我使用 __getstdClass数组转换为对象。但我不能决定我应该坚持。我想知道哪个更好更快,有什么想法吗?

class property 
{

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

$object = new property();
$object = new stdClass();

所以如果我使用new property(),我将得到一个属性对象输出,

property Object
(
....
)

如果我使用 new stdClass(),我将得到一个 stdClass 对象 输出,

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

最佳答案

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

也就是说,您的“命名”类比 stdClass 有一个优势是您可以通过利用 __get 来定义访问不存在的属性时发生的情况。魔术方法。

class property
{
public function __get($name)
{
return null;
}
}

以上是对原始 property 的简单重写类(class);什么时候__get()正在被调用,你已经知道 $this->$name未设置。虽然这不会引起通知,但它不会在您尝试引用 $obj->bla->bla 时阻止 fatal error 。其中 $obj->bla不存在。

当访问不存在的属性时抛出异常可能更有用:

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

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

关于PHP 对象 : property Object Vs stdClass Object - which one is better?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13371730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com