関数 get_object_vars

関数get_object_varsは、渡されたオブジェクトのプロパティを含む連想配列を返します。 返される配列のキーはプロパティ名、値は対応するプロパティの値となります。 この関数は、プロパティを取得したいオブジェクトという1つのパラメータを受け取ります。

構文

phpget_object_vars(object);

例

シンプルなオブジェクトのプロパティを取得します:

php<?php
  class MyClass {
    public $a = 1;
    public $b = 2;
    private $c = 3;
  }
  
  $obj = new MyClass();
  $res = get_object_vars($obj);
  print_r($res);
?>

コードの実行結果:

php['a' => 1, 'b' => 2]

例

この関数はprivateおよびprotectedプロパティを返しません:

php<?php
  class Test {
    public $x = 10;
    protected $y = 20;
    private $z = 30;
  }
  
  $test = new Test();
  $res = get_object_vars($test);
  print_r($res);
?>

コードの実行結果:

php['x' => 10]

例

動的プロパティとの連携:

php<?php
  $user = new stdClass();
  $user->name = 'John';
  $user->age = 25;
  
  $res = get_object_vars($user);
  print_r($res);
?>

コードの実行結果:

php['name' => 'John', 'age' => 25]

関連項目