Casting an Array with Numeric Keys as an Object

后端 未结 4 1267
余生分开走
余生分开走 2020-11-27 07:23

I was poking around PHPs casting mechanism, and ran into an odd case when casting an array as an object

$o = (object) array(\'1\'=>\'/foo/bar\');   
$o =          


        
4条回答
  •  一向
    一向 (楼主)
    2020-11-27 07:59

    Yes, they are just locked away unless cast back to an array.

    Maybe, the properties are still there and are accessible, just not directly. However, I'm not sure how foreach works internally (it might cast the object to an array) as I have not dived in the source code.

    Example:

    $array = array('one', 'two', 'three', 'four');
    $obj = (object) $array;
    
    foreach ($obj as $key => &$val) {
        print "$key -> $val
    "; $val = 'Nhaca'; var_dump($obj); } print_r($obj); print_r($array);

    output:

    0 -> one
    object(stdClass)[1]
      &string 'Nhaca' (length=5)
      string 'two' (length=3)
      string 'three' (length=5)
      string 'four' (length=4)
    1 -> two
    object(stdClass)[1]
      string 'Nhaca' (length=5)
      &string 'Nhaca' (length=5)
      string 'three' (length=5)
      string 'four' (length=4)
    2 -> three
    object(stdClass)[1]
      string 'Nhaca' (length=5)
      string 'Nhaca' (length=5)
      &string 'Nhaca' (length=5)
      string 'four' (length=4)
    3 -> four
    object(stdClass)[1]
      string 'Nhaca' (length=5)
      string 'Nhaca' (length=5)
      string 'Nhaca' (length=5)
      &string 'Nhaca' (length=5)
    stdClass Object ( [0] => Nhaca [1] => Nhaca [2] => Nhaca [3] => Nhaca ) 
    Array ( [0] => one [1] => two [2] => three [3] => four )
    

提交回复
热议问题