|
XII. Classes/Objects 類/物件函數
本類函數容許取得類和物件案例的訊息。可以取得物件所屬的類的名字,以及它的成員屬性和方法。通過使用這些函數,不僅可以弄清楚一個物件類的全體成員,而且可以知道它的起源(例如,該物件類是哪個類的增加)。
本增加模組作為 PHP 內核的一部分,無需安裝即可使用。 本增加模組在 php.ini 中未定義任何配置選項。
在本例子中,先定義一個基礎類和一個增加類。基礎類描述的是普通的蔬菜(Vegetable),它是否可食用(is_edible)以及它是什麼彩色(what_color)。子類
Spinach 增加了「烹調」的方法(cook_it)和「獲知它是否已被烹調了」的方法(is_cooked)。
例子 1. classes.inc
<?php
// 基類及其成員屬性與方法 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; }
} // Vegetable 類定義結束
// 增加基類 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; }
} // Spinach 類定義結束
?>
|
|
接著,從這些物件中建立兩個物件案例,列印出它們的關聯訊息,內含它們的起源。還定義了一些實用函數,它們主要是為了讓變量的輸出好看些。
例子 2. test_script.php
<pre> <?php
include "classes.inc";
// utility functions
function print_vars($obj) { foreach (get_object_vars($obj) as $prop => $val) { echo "\t$prop = $val\n"; } }
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 $class\n"; } else { echo "Object $obj does not belong to a subclass of $class\n"; } }
// instantiate 2 objects
$veggie = new Vegetable(true, "blue"); $leafy = new Spinach();
// print out information about objects echo "veggie: CLASS " . get_class($veggie) . "\n"; echo "leafy: CLASS " . get_class($leafy); echo ", PARENT " . get_parent_class($leafy) . "\n";
// show veggie properties echo "\nveggie: Properties\n"; print_vars($veggie);
// and leafy methods echo "\nleafy: Methods\n"; print_methods($leafy);
echo "\nParentage:\n"; class_parentage("leafy", "Spinach"); class_parentage("leafy", "Vegetable"); ?> </pre>
|
上邊例子中重點要注意的是物件
$leafy 是
Spinach 類的一個案例,而
Spinach 類是
Vegetable 類的一個子類,因此上邊腳本的最後部分將會輸出:
[...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach a subclass of Vegetable |
|
| |