【问题标题】:PHP: serialize as array an object via (array) $objectPHP:通过 (array) $object 将对象序列化为数组
【发布时间】:2015-04-03 19:24:09
【问题描述】:

有没有办法在调用这段代码的时候把一个对象序列化成一个数组:

class Obj {
    private $prop;
    public function __construct($v) {
       $this->prop = $v;
    }
}

$object = new Obj('value');
$result = (array) $object;

print_r($result);

// should display something like Array ( prop => value )
// via a magic function call in the object ?

一些 ArrayObject、Traversable 和其他东西可以帮助在 foreach、count() 等中使用对象。但是使用强制类型数组语法,我们能做什么呢?

谢谢

编辑 我发现这篇文章比我的问题更好地解释了:) Casting object to array - any magic method being called?

答案是:不,调用(array)$object时不能要求魔法方法

【问题讨论】:

    标签: php arrays object


    【解决方案1】:

    您的代码是正确的,但属性 prop 是私有的,因此当您尝试打印时将返回如下内容:

    Array
    (
        [Objprop] => value
    )
    

    为了返回 prop 作为密钥,您应该公开您的财产 或者你可以制作getter函数:

    public function getV(){
         return $this->v;
    }
    

    【讨论】:

      【解决方案2】:

      get_object_vars 在从正确范围调用时忽略可见性声明:

      class Obj {
          private $prop;
          public function __construct($v) {
              $this->prop = $v;
          }
          public function asArray() {
              return get_object_vars($this);
          }
      }
      
      $object = new Obj('value');
      $result = $object->asArray();
      
      print_r($result); // Array([prop] => value)
      

      【讨论】:

      • 好的,所以 clone $object 没有像 function __clone() 这样的东西。例如,function __toArray() 代表 (array) $object
      • 你的意思是,像__toString 用于数组?不,没有这样的事情,AFAIK。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 2020-12-16
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多