【问题标题】:How can I convert an object to associative array in PHP?如何在 PHP 中将对象转换为关联数组?
【发布时间】:2011-04-30 04:08:11
【问题描述】:

正如标题所示,我的问题是如何将 php 类转换为关联数组? 例如我有

class MyObject {
  private $size = null;
  private $length = null;
  private $width = null;

    public function getSize(){
        return $this->size;
    }

    public function setSize($size){
        $this->size = $size;
    }

    public function getLength(){
        return $this->length;
    }

    public function setLength($length){
        $this->length = $length;
    }

    public function getWidth(){
        return $this->width;
    }

    public function setWidth($width){
        $this->width = $width;
    }

}

//Now what i want is following

$abc = new MyObject();
$abc->width = 10;
$anArray = someFunction($abc);  
//This should generate an associative array
//Now associative array is accessible
echo $anArray['width]; // 10

【问题讨论】:

    标签: php


    【解决方案1】:

    有两种工作方式略有不同。

    您可以强制转换为数组:

    $array = (array)$object;
    

    有一章是关于细节和副作用的in the PHP manual

    或使用get_object_vars()

    请参阅 this question 了解差异。

    【讨论】:

    • 您能否定义如何使用 get_object_vars() 构建关联数组?
    • @Aqeel 抱歉,如果现在遇到这种粗鲁的行为,但在要求 Pekka 向您提供代码之前,您真的 RTFM 吗?如果是这样,请指出是什么造成了困难。
    • @Gordon 对不起,我有点困惑,我已经解决了我的问题。谢谢。
    猜你喜欢
    • 2011-05-19
    • 2016-03-29
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 2022-11-22
    相关资源
    最近更新 更多