我已经获得了以下代码片段,效果非常好。我一直在对它进行分析,而且代码的使用次数很多,所以我想弄清楚如何以比当前写入方式更好的方式编写代码。
有没有更有效的方法来写这个?
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
// Return array converted to object Using __FUNCTION__ (Magic constant) for recursive call
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
答案 0 :(得分:1)
您可以对需要转换的类实现toArray()
方法:
e.g。
class foo
{
protected $property1;
protected $property2;
public function __toArray()
{
return array(
'property1' => $this->property1,
'property2' => $this->property2
);
}
}
在我看来,有权访问受保护的属性并将整个转换封装在类中是最好的方法。
<强>更新强>
有一点需要注意的是,get_object_vars()
函数只会返回可公开访问的属性 - 可能不是您所追求的。
如果上述内容过于简单,那么来自课外的准确方式将使用ReflectionClass
内置的PHP(SPL):
$values = array();
$reflectionClass = new \ReflectionClass($object);
foreach($reflectionClass->getProperties() as $property) {
$values[$property->getName()] = $property->getValue($object);
}
var_dump($values);
答案 1 :(得分:0)
取决于它是什么类型的对象,许多标准的php对象都有内置的方法来转换它们
例如,MySQLi结果可以像这样转换
$resultArray = $result->fetch_array(MYSQLI_ASSOC);
如果它是一个自定义类对象,你可能会考虑在那个类中实现一个方法,因为AlexP sugested
答案 2 :(得分:0)
结束:
function objectToArray($d) {
$d = (object) $d;
return $d;
}
function arrayToObject($d) {
$d = (array) $d;
return $d;
}
答案 3 :(得分:0)
正如AlexP所说,你可以实现一个方法__toArray()。作为ReflexionClass(复杂且昂贵)的替代方案,使用object iteration properties,您可以按照以下方式迭代$this
class Foo
{
protected $var1;
protected $var2;
public function __toArray()
{
$result = array();
foreach ($this as $key => $value) {
$result[$key] = $value;
}
return $result;
}
}
这也将迭代未在类中定义的对象属性:例如
$foo = new Foo;
$foo->var3 = 'asdf';
var_dump($foo->__toArray());)