PHPマニュアル/PEARマニュアル | ユーザフォーラムで議論/質問 | マニュアル検索 | ハイライト | ハイライトオフ | ポータル | php spot

| JavaScript入門&応用&リファレンスなら「JavaScriptist」

  

この例では、まず基底クラスおよびそのクラスの派生クラスを定義します。 基底クラスは食用か否か、色とかいった、一般的な野菜を記述します。 サブクラス Spinach は、 その野菜の料理法と調理済であるかどうかの情報を追加します。

例1 classes.inc

<?php

// メンバープロパティとメソッドを有する基底クラス
class Vegetable {

   var 
$edible;
   var 
$color;

   function 
__construct($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 
__construct()
   {
       
parent::__construct(true"green");
   }

   function 
cook_it() 
   {
       
$this->cooked true;
   }

   function 
is_cooked() 
   {
       return 
$this->cooked;
   }
   
// クラスSpinachの終り

?>

続いて、これらのクラスから二つのオブジェクトのインスタンスを作成し、 親クラスを含む情報を出力します。 また、いくつかのユーティリティ関数を定義します。これらは主に変数 を格好良く表示するためのものです。

例2 test_script.php

<pre>
<?php

include "classes.inc";

// ユーティリティ関数

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($GLOBALS[$obj]);
    echo 
", a subclass of $class\n";
} else {
    echo 
"Object $obj does not belong to a subclass of $class\n";
}
}

// 二つのオブジェクトのインスタンスを作成

$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";

// veggieのプロパティを表示
echo "\nveggie: Properties\n";
print_vars($veggie);

// そしてleafyのメソッドを表示
echo "\nleafy: Methods\n";
print_methods($leafy);

echo 
"\nParentage:\n";
class_parentage("leafy""Spinach");
class_parentage("leafy""Vegetable");
?>
</pre>

注意すべき大事な点ですが、上記の例ではオブジェクト $leafyVegetableのサブクラスであるクラス Spinachのインスタンスであり、 このスクリプトの最後の部分は以下のような出力となります。

   [...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach, a subclass of Vegetable


忘却曲線を使ってこの知識を確実に記憶に残す

フォーラムで「」について話す
各種マニュアル: PHPマニュアル | PEARマニュアル | Smarty(英語)マニュアル | PHP-GTKマニュアル | 」をGoogle検索
copyright © 1997-2024 PHP ドキュメント作成グループ(ライセンス). provided by php spot. マニュアル: