Array to Object and Object to Array in PHP - interesting behaviour

后端 未结 2 1776
萌比男神i
萌比男神i 2020-11-30 09:06

Can you explain the next interesting behaviour?

class test {
  //Class *test* has two properties, public and private.
  public $xpublic = \'x1\';
  private $         


        
相关标签:
2条回答
  • 2020-11-30 09:27

    The array key contains a marker that this should be a private property of the class test.

    Compare your scripts output with the following:

    $array = array(
        "xpublic" => "x1", 
        # this will become a private member:
        "\x00test\x00xprivate" => "x2",
        # this will become a protected member:
        "\x00*\x00xprotected" => "x3"
    );
    
    var_dump($array);
    
    $obj = (object) $array;
    
    var_dump($obj);
    

    When serialized, the same string is used to describe the private members.

    Output:

    array(3) {
      ["xpublic"]=>
      string(2) "x1"
      ["testxprivate"]=>
      string(2) "x2"
      ["*xprotected"]=>
      string(2) "x3"
    }
    
    object(stdClass)#1 (3) {
      ["xpublic"]=>
      string(2) "x1"
      ["xprivate":"test":private]=>
      string(2) "x2"
      ["xprotected":protected]=>
      string(2) "x3"
    }
    

    In the output of var_dump(), the null bytes are not visible.

    (Update: Added protected class member)

    0 讨论(0)
  • 2020-11-30 09:37

    Probably the PHP engine conserves the class structure internaly and simply gives some kind of an array wrapper, and thus when you cast it again it remains private, though I can't assure this at 100%.

    0 讨论(0)
提交回复
热议问题