関数 get_object_vars
関数get_object_varsは、渡されたオブジェクトのプロパティを含む連想配列を返します。
返される配列のキーはプロパティ名、値は対応するプロパティの値となります。
この関数は、プロパティを取得したいオブジェクトという1つのパラメータを受け取ります。
構文
get_object_vars(object);
例
シンプルなオブジェクトのプロパティを取得します:
<?php
class MyClass {
public $a = 1;
public $b = 2;
private $c = 3;
}
$obj = new MyClass();
$res = get_object_vars($obj);
print_r($res);
?>
コードの実行結果:
['a' => 1, 'b' => 2]
例
この関数はprivateおよびprotectedプロパティを返しません:
<?php
class Test {
public $x = 10;
protected $y = 20;
private $z = 30;
}
$test = new Test();
$res = get_object_vars($test);
print_r($res);
?>
コードの実行結果:
['x' => 10]
例
動的プロパティとの連携:
<?php
$user = new stdClass();
$user->name = 'John';
$user->age = 25;
$res = get_object_vars($user);
print_r($res);
?>
コードの実行結果:
['name' => 'John', 'age' => 25]
関連項目
-
クラスのプロパティを返す関数 get_class_vars,
-
プロパティの存在を確認する関数 property_exists,
-
すべての変数を返す関数 get_defined_vars,