1. interface_exists、class_exists、method_exists和property_exists:
顾名思义,从以上几个函数的命名便可以猜出几分他们的功能。我想这也是我随着对PHP的深入学习而越来越喜欢这门
编程语言的原因了吧。下面先给出他们的原型声明和简短说明,更多的还是直接看例子代码吧。
bool interface_exists (string $interface_name [, bool $autoload = true ]) 判断接口是否存在,第二个参数表示在查找时是否执行__autoload。
bool class_exists (string $class_name [, bool $autoload = true ]) 判断类是否存在,第二个参数表示在查找时是否执行__autoload。
bool method_exists (mixed $object , string $method_name) 判断指定类或者对象中是否含有指定的成员函数。
bool property_exists (mixed $class , string $property) 判断指定类或者对象中是否含有指定的成员变量。
<?php
//in another_test_class.php
interface AnotherTestInterface {
}
class AnotherTestClass {
public static function printMe() {
print "This is Test2::printSelf.\n";
}
public function doSomething() {
print "This is Test2::doSomething.\n";
}
public function doSomethingWithArgs($arg1, $arg2) {
print 'This is Test2::doSomethingWithArgs with ($arg1 = '.$arg1.' and $arg2 = '.$arg2.").\n";
}
}
<?php
//in class_exist_test.php, 下面测试代码中所需的类和接口位于another_test_class.php,
//由此可以发现规律,类和接口的名称是驼峰风格的,而文件名的单词间是下划线分隔的。
//这里给出了两种__autoload的方式,因为第一种更为常用和方便,因此我们这里将第二种方式注释掉了,他们之间的差别可以查看manual。
function __autoload($classname) {
$nomilizedClassname = strtolower(preg_replace('/([A-Z]\w*)([A-Z]\w*)([A-Z]\w*)/','${1}_${2}_${3}',$classname));
require strtolower($nomilizedClassname).".php";
}
//spl_autoload_register(function($classname) {
// $nomilizedClassname = strtolower(preg_replace('/([A-Z]\w*)([A-Z]\w*)([A-Z]\w*)/','${1}_${2}_${3}',$classname));
// require strtolower($nomilizedClassname).".php";
//});
print "The following case is tested before executing autoload.\n";
if (!class_exists('AnotherTestClass',false)) {
print "This class doesn't exist if no autoload.\n";
}
if (!interface_exists('AnotherTestInterface',false)) {
print "This interface doesn't exist if no autoload.\n";
}
print "\nThe following case is tested after executing autoload.\n";
if (class_exists('AnotherTestClass',true)) {
print "This class exists if autoload is set to true.\n";
}
if (interface_exists('AnotherTestInterface',true)) {
print "This interface exists if autoload is set to true.\n";
}
运行结果如下:
bogon:TestPhp$ php class_exist_test.php
The following case is tested before executing autoload.
This class doesn't exist if no autoload.
This interface doesn't exist if no autoload.
The following case is tested after executing autoload.
This class exists if autoload is set to true.
2. get_declared_classes和get_declared_interfaces:
分别返回当前可以访问的所有类和接口,这不仅包括自定义类和接口,也包括了