PHPのオブジェクトへの変換を試してみた

PHP の変数って型キャストをすることでオブジェクトに変換できるのは知ってたんだけど、実際どの型がどうなるっていうのは把握してなかったので、ちょっと試してみた。

結論から言うと、

  • いずれも stdClass のインスタンスとなる
  • スカラー変数(bool, string, int, float) は scalar というプロパティに値がそのまま代入される
  • null と添字配列は空のインスタンスとなる
  • 連想配列は、キーがプロパティ名、値がプロパティの値になる

ということに。添字配列がかなり意外だった。

サンプルコードは以下。

 <?php
 $bool = false;
 $int = 10;
 $float = 4.23;
 $string = 'ebi';
 $null = null;
 $indexedArray = array('ebi', 'kani', 'sasori', 'zarigani');
 $associativeArray = array('o-hira' => 'teriyaki', 'ogawa' => 'balibali', 'ebihara' => 'co3k');

 Reflection::export(new ReflectionObject((object)$bool));
 echo "---------\n"; 
 Reflection::export(new ReflectionObject((object)$int));
 echo "---------\n";
 Reflection::export(new ReflectionObject((object)$float));
 echo "---------\n";
 Reflection::export(new ReflectionObject((object)$string));
 echo "---------\n";
 Reflection::export(new ReflectionObject((object)$null));
 echo "---------\n";
 Reflection::export(new ReflectionObject((object)$indexedArray));
 echo "---------\n";
 Reflection::export(new ReflectionObject((object)$associativeArray));
bool, int, float, string の結果
Object of class [ <internal> class stdClass ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Dynamic properties [1] {
    Property [ <dynamic> public $scalar ]
  }

  - Methods [0] {
  }
}
null, 添字配列 の結果
---------
Object of class [ <internal> class stdClass ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Dynamic properties [0] {
  }

  - Methods [0] {
  }
}
連想配列の結果
Object of class [ <internal> class stdClass ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Dynamic properties [3] {
    Property [ <dynamic> public $o-hira ]
    Property [ <dynamic> public $ogawa ]
    Property [ <dynamic> public $ebihara ]
  }

  - Methods [0] {
  }
}