将对象转换为数组PHP - 仅限公共字段

Kel*_*all 3 php oop object

我想在PHP中将对象转换为数组 - 但只是公共字段.我发现了一些关于在PHP中将对象转换为数组的答案,但它们都转换了所有字段(也是私有的).我只需要公共领域 - 我怎样才能做到这一点?

Rya*_*yan 8

通过使用get_object_vars()

例:

$object_to_arr = get_object_vars($obj);
Run Code Online (Sandbox Code Playgroud)

get_object_vars() 只返回对象的可访问和非静态属性.

编辑:

如果你直接运行它,$this那么它将返回private属性.这是因为private类本身甚至可以访问属性.

要解决这个问题,请执行以下操作:

$i = $this; 
$publics_only = function() use ($i) { 
    return get_object_vars($i); 
}; 
return $publics_only(); 
Run Code Online (Sandbox Code Playgroud)