gpt4 book ai didi

php - 如何在 PHP 中将对象转换(转换)为没有类名前缀的数组?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:54:22 25 4
gpt4 key购买 nike

如何在 PHP 中将对象转换(转换)为没有类名前缀的数组?

class Teste{

private $a;
private $b;

function __construct($a, $b) {
$this->a = $a;
$this->b = $b;
}

}

var_dump((array)(new Teste('foo','bar')));

结果:

array
'�Teste�a' => string 'foo' (length=3)
'�Teste�b' => string 'bar' (length=3)

预期:

array (
a => 'foo'
b => 'bar' )

最佳答案

来自manual :

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour:

因此,您可以像这样解决这个问题:

$temp = (array)(new Teste('foo','bar'));
$array = array();
foreach ($temp as $k => $v) {
$k = preg_match('/^\x00(?:.*?)\x00(.+)/', $k, $matches) ? $matches[1] : $k;
$array[$k] = $v;
}
var_dump($array);

没有办法控制/禁用这种行为,这似乎很奇怪,因为没有碰撞的风险。

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

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