查詢

get_object_vars()函式—用法及示例

「 返回指定物件的屬性和屬性值的關聯陣列 」


函式名稱:get_object_vars()

適用版本:所有PHP版本

函式描述:get_object_vars() 函式用於返回指定物件的屬性和屬性值的關聯陣列。

語法:get_object_vars(object $object): array

引數:

  • $object:必需。要獲取屬性的物件。

返回值:返回一個關聯陣列,其中鍵表示屬性名,值表示屬性值。

示例:

class Student {
    public $name;
    protected $age;
    private $grade;

    public function __construct($name, $age, $grade) {
        $this->name = $name;
        $this->age = $age;
        $this->grade = $grade;
    }
}

$student = new Student("John", 18, "A");

$properties = get_object_vars($student);

print_r($properties);

輸出:

Array
(
    [name] => John
    [age] => 18
    [grade] => A
)

在上面的示例中,我們定義了一個名為Student的類,並建立了一個名為$student的物件。然後,我們使用get_object_vars()函式獲取了$student物件的屬性和屬性值,並將結果儲存在$properties變數中。最後,我們使用print_r()函式列印了$properties陣列,顯示了物件的屬性和屬性值。

補充糾錯
上一個函式: get_parent_class()函式
下一個函式: get_meta_tags()函式
熱門PHP函式
分享連結