How to convert (cast) Object to Array without Class Name prefix in PHP?

后端 未结 4 647
被撕碎了的回忆
被撕碎了的回忆 2021-02-10 11:16

How to convert (cast) Object to Array without Class Name prefix in PHP?

class Teste{

    private $a;
    private $b;

    function __construct($a, $b) {
                


        
4条回答
  •  走了就别回头了
    2021-02-10 11:56

    From the 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:

    You can therefore work around the issue like this:

    $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);
    

    It does seem odd that there is no way to control/disable this behaviour, since there is no risk of collisions.

提交回复
热议问题