一、概述和安装
这些函数允许你获得类和对象实例的相关信息。 你可以获取对象所属的类名,也可以是它的成员属性和方法。 通过使用这些函数,你不仅可以找到对象和类的关系,也可以是它们的继承关系(例如,对象类继承自哪个类)。
请参考面向对象相关章节来查看在 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 — 如果对象属于该类或该类是此对象的父类则返回 TRUE
is_subclass_of — 如果此对象是该类的子类,则返回 TRUE
method_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 = $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";
}
}
// 实例化 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: 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");
?>
一个重要的东西是注意在上面的例子中,对象 $leafy 是 Spinach 的实例(Vegetable 的子类),另外脚本的最后部分会输出以下信息:[...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach a subclass of Vegetable
本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉
本文系统来源:php中文网