BlaBla.cn

PHP: Classes/Objects - Manual

BlaBla.cn
call_user_method_array > <ccvs_void
Last updated: Wed, 19 Mar 2008

Classes/Objects 类/对象函数

简介

本类函数允许获取类和对象实例的信息。可以取得对象所属的类的名字,以及它的成员属性和方法。通过使用这些函数,不仅可以弄清楚一个对象类的全体成员,而且可以知道它的起源(例如,该对象类是哪个类的扩展)。

需求

要编译本扩展模块无需外部库文件。

安装

本扩展模块作为 PHP 内核的一部分,无需安装即可使用。

运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。

资源类型

本扩展模块未定义任何资源类型。

预定义常量

本扩展模块未定义任何常量。

范例

在本例子中,先定义一个基础类和一个扩展类。基础类描述的是普通的蔬菜(Vegetable),它是否可食用(is_edible)以及它是什么颜色(what_color)。子类 Spinach 增加了“烹调”的方法(cook_it)和“获知它是否已被烹调了”的方法(is_cooked)。

Example#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 类定义结束

?>

接着,从这些对象中创建两个对象实例,打印出它们的相关信息,包括它们的起源。还定义了一些实用函数,它们主要是为了让变量的输出好看些。

Example#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>

上边例子中重点要注意的是对象 $leafySpinach 类的一个实例,而 Spinach 类是 Vegetable 类的一个子类,因此上边脚本的最后部分将会输出:

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

     

Table of Contents



call_user_method_array > <ccvs_void
Last updated: Wed, 19 Mar 2008
 

 
BlaBla.cn

© 2005-2008 BlaBla.cn 版权所有