PHP对象转换为数组array(object) 数组值读取
$objecta
class objecta {
protected $temp;
}
$arr = (array)$objecta;
$arr 怎样读取 temp值?
$arr['temp'],$arr['*temp'] 都读取不到
官方说明:
如果一个 object 类型转换为 array,则结果为一个数组,其单元为该对象的属性。键名将为成员变量名,不过有几点例外:整数属性不可访问;私有变量前会加上类名作前缀;保护变量前会加上一个 '*' 做前缀。这些前缀的前后都各有一个 NULL 字符。这会导致一些不可预知的行为:
<?php
class A {
private $A; // This will become '\0A\0A'
}
class B extends A {
private $A; // This will become '\0B\0A'
public $AA; // This will become 'AA'
}
var_dump((array) new B());
?>
<?php
class objecta implements arrayaccess {
public $temp = 1;
public function offsetSet($offset, $value) {
var_dump(__METHOD__);
}
public function offsetExists($var) {
var_dump(__METHOD__);
if ($var == "foobar") {
return true;
}
return false;
}
public function offsetUnset($var) {
var_dump(__METHOD__);
}
public function offsetGet($var) {
var_dump(__METHOD__);
return "value";
}
}
$obj = new objecta();
echo $obj['temp'];
我觉得还是类型的原因。protect
和private
的属性本来就不能从外部获取到吧,我试了一下只有public
的属性能获取到。
感觉还是用 ArrayAccess 吧, 最简单的数组形式访问对象,直接在你的类上实现该接口。反射之类的用在这有点怪怪的呢、
class Obj implements \ArrayAccess
{
}
\ArrayAccess 接口的结构,你的类必须要实现这些方法。
ArrayAccess {
/* 方法 */
abstract public boolean offsetExists ( mixed $offset )
abstract public mixed offsetGet ( mixed $offset )
abstract public void offsetSet ( mixed $offset , mixed $value )
abstract public void offsetUnset ( mixed $offset )
}
小示例、
class Obj implements \ArrayAccess
{
protected $_data = 'data aaa';
/**
* 检查数组键是否存在,本例中对象成员就是数组元素、
* 对一个实现了 ArrayAccess 接口的对象使用 isset() 或 empty() 时,此方法将执行。
* ~~~
* $obj = new Obj();
* var_dump(isset($obj['_data']));
* ~~~
* @param mixed $offset 要检查的键名
* @return boolean
*/
public function offsetExists($offset) {
return array_key_exists($offset, get_object_vars($this));
}
/**
* 检查数组键是否存在,在本例中我们把键设置为
* 对一个实现了 ArrayAccess 接口的对象使用 isset() 或 empty() 时,此方法将执行。
* ~~~
* $obj = new Obj();
* unset($obj['_data']);
* var_dump(isset($obj['_data']));
* ~~~
* @param mixed $offset 要检查的键名
* @return boolean
*/
public function offsetUnset($key) {
if (array_key_exists($key,get_object_vars($this)) ) {
unset($this->{$key});
}
}
/**
* 累了不写了这个是设置数组成员,本例中就是对象属性、
*/
public function offsetSet($offset, $value) {
$this->{$offset} = $value;
}
public function offsetGet($var) {
return $this->$var;
}
}
$obj = new Obj();
echo $obj['_data'];
不好意思,回答时激情满满,写几行就枯燥了、后俩没注释你自己翻资料去吧、
我觉得你应该实现ArrayAccess接口
<?php
class Objecta {
protected $protected_val = 'default_protected';
public $public_val = 'default_public';
private $private_val = 'default_private';
public function __construct($params)
{
$this->public_val = $params['public'];
}
}
$object2array = function ($object) {
$ref = new ReflectionClass($object);
$props = $ref->getProperties();
$arr = [];
foreach ($props as $prop) {
$prop->setAccessible(true);
$arr[$prop->getName()] = $prop->getValue($object);
$prop->setAccessible(false);
}
return $arr;
};
$result = $object2array(new Objecta([
'public' => 'public_val',
]));
var_dump($result);