get_object_vars() 回傳物件所有可見屬性組成的關聯陣列,鍵為屬性名,值為屬性值。適用於物件序列化、除錯輸出、屬性遍歷等場景。
array get_object_vars(object $object)
回傳關聯陣列,包含 public、protected(在類別內部呼叫時)、private(在定義該屬性的類別內部呼叫時)屬性。
class Person {
public $name = "王美人";
public $age = 25;
public $birth;
}
$p = new Person();
print_r(get_object_vars($p));
輸出:
Array (
[name] => 王美人
[age] => 25
[birth] =>
)
interface Arrayable {
public function toArray();
}
class User implements Arrayable {
public $id;
public $name;
protected $email;
private $password;
public function toArray() {
return get_object_vars($this); // 類別內部可見 protected/private
}
}
$user = new User();
$user->id = 1;
$user->name = "張三";
$user->email = "zhang@example.com"; // 假設有 setter
$user->password = "secret";
print_r($user->toArray());
輸出包含所有四個屬性,因在類別內部呼叫。
nullpublic 屬性