PHP變量與類型擴展之類與對象
這些函數允許你獲得類和對象實例的相關信息。 你可以獲取對象所屬的類名,也可以是它的成員屬性和方法。 通過使用這些函數,你不僅可以找到對象和類的關系,也可以是它們的繼承關系(例如,對象類繼承自哪個類)。
請參考面向對象相關章節來查看在 PHP 里,對象和類如何實現和使用的詳細描述。
使用這些函數不需要安裝,它們是 PHP 核心的一部分。
二、類與對象函數大全__autoload?— 嘗試加載未定義的類call_user_method_array?— 調用一個用戶方法,同時傳遞參數數組(已廢棄)call_user_method?— 對特定對象調用用戶方法(已廢棄)class_alias?— 為一個類創建別名class_exists?— 檢查類是否已定義get_called_class?— 后期靜態綁定('Late Static Binding')類的名稱get_class_methods?— 返回由類的方法名組成的數組get_class_vars?— 返回由類的默認屬性組成的數組get_class?— 返回對象的類名get_declared_classes?— 返回由已定義類的名字所組成的數組get_declared_interfaces?— 返回一個數組包含所有已聲明的接口get_declared_traits?— 返回所有已定義的 traits 的數組get_object_vars?— 返回由對象屬性組成的關聯數組get_parent_class?— 返回對象或類的父類名interface_exists?— 檢查接口是否已被定義is_a?— 如果對象屬于該類或該類是此對象的父類則返回 TRUEis_subclass_of?— 如果此對象是該類的子類,則返回 TRUEmethod_exists?— 檢查類的方法是否存在property_exists?— 檢查對象或類是否具有該屬性trait_exists?— 檢查指定的 trait 是否存在三、使用范例在這個例子中,我們首先定義了一個基類和該類的擴展。 這個基類描述了普通的蔬菜,關于它是否可食用及其顏色。 子類?Spinach?添加了烹飪的方法和另一個檢查是否已烹飪的方法。
Example #1 classes.inc
<?php // base class with member properties and methods class Vegetable {var $edible;var $color;function Vegetable($edible, $color='green') { $this->edible = $edible; $this->color = $color;}function is_edible() { return $this->edible;}function what_color() { return $this->color;} } // end of class Vegetable // extends the base class class Spinach extends Vegetable { var $cooked = false; function Spinach(){ $this->Vegetable(true, 'green'); } function cook_it(){ $this->cooked = true; } function is_cooked(){ return $this->cooked; } } // end of class Spinach?>
接下來我們從這些類中實例化了兩個對象,并打印了他們的信息,包括了他們類的繼承關系。 同時我們也定了一些實用函數,主要為了漂亮地打印出這些變量。
Example #2 test_script.php
<?php include 'classes.inc'; // 實用函數 function print_vars($obj) {foreach (get_object_vars($obj) as $prop => $val) { echo 't$prop = $valn';} } function print_methods($obj) {$arr = get_class_methods(get_class($obj));foreach ($arr as $method) { echo 'tfunction $method()n';} } function class_parentage($obj, $class) {if (is_subclass_of($GLOBALS[$obj], $class)) { echo 'Object $obj belongs to class ' . get_class($$obj); echo ' a subclass of $classn';} else { echo 'Object $obj does not belong to a subclass of $classn';} } // 實例化 2 對象 $veggie = new Vegetable(true, 'blue'); $leafy = new Spinach(); // 打印這些對象的信息 echo 'veggie: CLASS ' . get_class($veggie) . 'n'; echo 'leafy: CLASS ' . get_class($leafy); echo ', PARENT ' . get_parent_class($leafy) . 'n'; // 顯示蔬菜的屬性 echo 'nveggie: Propertiesn'; print_vars($veggie); // and leafy methods echo 'nleafy: Methodsn'; print_methods($leafy); echo 'nParentage:n'; class_parentage('leafy', 'Spinach'); class_parentage('leafy', 'Vegetable');?>
一個重要的東西是注意在上面的例子中,對象?$leafy?是?Spinach?的實例(Vegetable?的子類),另外腳本的最后部分會輸出以下信息:
[...]Parentage:Object leafy does not belong to a subclass of SpinachObject leafy belongs to class spinach a subclass of Vegetable
相關文章:
