gpt4 book ai didi

php - 如何在 PHP 中将对象转换为关联数组?

转载 作者:行者123 更新时间:2023-12-02 07:50:40 24 4
gpt4 key购买 nike

如标题所示,我的问题是如何将 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

最佳答案

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

你可以转换成一个数组:

$array = (array)$object;

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

或使用 get_object_vars() .

参见 this question关于差异。

关于php - 如何在 PHP 中将对象转换为关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4014134/

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