PHP类和对象函数实例详解

摘要:
我想这也是我随着对PHP的深入学习越来越喜欢这种编程语言的原因。boolmethod_Exists确定指定的类或对象是否包含指定的成员函数。它们的函数声明非常简单。它们没有参数,只有返回数组。例如,如果在类内部调用,则所有成员函数或变量都满足条件,而在类外部,只能返回公共函数和变量。arrayget_class_方法获取指定类中可访问的成员函数。

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.
";
    }
    public function doSomething() {
        print "This is Test2::doSomething.
";
    }
    public function doSomethingWithArgs($arg1, $arg2) {
        print 'This is Test2::doSomethingWithArgs with ($arg1 = '.$arg1.' and $arg2 = '.$arg2.").
";
    }
}

<?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.
";
if (!class_exists('AnotherTestClass',false)) {
    print "This class doesn't exist if no autoload.
";
}

if (!interface_exists('AnotherTestInterface',false)) {
    print "This interface doesn't exist if no autoload.
";
}

print "
The following case is tested after executing autoload.
";
if (class_exists('AnotherTestClass',true)) {
    print "This class exists if autoload is set to true.
";
}

if (interface_exists('AnotherTestInterface',true)) {
    print "This interface exists if autoload is set to true.
";
} 

    运行结果如下: 

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.
This interface exists if autoload is set to true.

2. get_declared_classes和get_declared_interfaces: 

    分别返回当前可以访问的所有类和接口,这不仅包括自定义类和接口,也包括了PHP内置类和接口。他们的函数声明非常简单,没有参数,只是返回数组。见如下代码:

<?php
interface AnotherTestInterface {

}

class AnotherTestClass {
    public static function printMe() {
        print "This is Test2::printSelf.
";
    }
}

print_r(get_declared_interfaces());
print_r(get_declared_classes());

    由于输出结果过长,而且这两个函数也比较简单,所以下面就不再给出输出结果了。

3. get_class_methods、get_class_vars和get_object_vars: 

    这三个函数有一个共同点,即只能获取作用域可见范围内的所有成员函数、成员变量或非静态成员变量。比如在类的内部调用,则所有成员函数或者变量都符合条件,而在类的外部,则只有共有的函数和变量可以返回。
array get_class_methods (mixed $class_name)获取指定类中可访问的成员函数。
array get_class_vars (string $class_name)获取指定类中可以访问的成员变量。
array get_object_vars (object $object) 获取可以访问的非静态成员变量。

<?php
function output_array($functionName, $items) {
    print "$functionName.....................
";
    foreach ($items as $key => $value) {
        print '$key = '.$key. ' => $value = '.$value."
";
    }
}

class TestClass {
    public $publicVar = 1;
    private $privateVar = 2;
    static private $staticPrivateVar = "hello";
    static public $staticPublicVar;

    private function privateFunction() {

    }
    function publicFunction() {
        output_array("get_class_methods",get_class_methods(__CLASS__));
        output_array('get_class_vars',get_class_vars(__CLASS__));
        output_array('get_object_vars',get_object_vars($this));
    }
}

$testObj = new TestClass();
print "The following is output within TestClass.
";
$testObj->publicFunction();

print "
The following is output out of TestClass.
";
output_array('get_class_methods',get_class_methods('TestClass'));
output_array('get_class_vars',get_class_vars('TestClass'));
output_array('get_object_vars',get_object_vars($testObj));

    运行结果如下:

bogon:TestPhp liulei$ php class_exist_test.php 
The following is output within TestClass.
get_class_methods.....................
$key = 0 => $value = privateFunction
$key = 1 => $value = publicFunction
get_class_vars.....................
$key = publicVar => $value = 1
$key = privateVar => $value = 2
$key = staticPrivateVar => $value = hello
$key = staticPublicVar => $value = 
get_object_vars.....................
$key = publicVar => $value = 1
$key = privateVar => $value = 2

The following is output out of TestClass.
get_class_methods.....................
$key = 0 => $value = publicFunction
get_class_vars.....................
$key = publicVar => $value = 1
$key = staticPublicVar => $value = 
get_object_vars.....................
$key = publicVar => $value = 1

4. get_called_class和get_class:

string get_class ([ object $object = NULL ])获取参数对象的类名称。
string get_called_class (void)静态方法调用时当前的类名称。

<?php
class Base {
    static public function test() {
        var_dump(get_called_class());
    }
}

class Derive extends Base {
}

Base::test();
Derive::test();

var_dump(get_class(new Base()));
var_dump(get_class(new Derive()));

    运行结果如下:

bogon:TestPhp$ php another_test_class.php 
string(4) "Base"
string(6) "Derive"
string(4) "Base"
string(6) "Derive"

5. get_parent_class、is_a和is_subclass_of:

    这三个函数都是和类的继承相关,所以我把他们归到了一起。

string get_parent_class ([ mixed $object ])获取参数对象的父类,如果没有父类则返回false。
bool is_a (object $object, string $class_name) 判断第一个参数对象是否是$class_name类本身或是其父类的对象。
bool is_subclass_of (mixed $object, string $class_name)判断第一个参数对象是否是$class_name的子类。

<?php
class Base {
    static public function test() {
        var_dump(get_called_class());
    }
}

class Derive extends Base {
}

var_dump(get_parent_class(new Derive()));
var_dump(is_a(new Derive(),'Derive'));
var_dump(is_a(new Derive(),'Base'));
var_dump(is_a(new Base(),'Derive'));

var_dump(is_subclass_of(new Derive(),'Derive'));
var_dump(is_subclass_of(new Derive(),'Base'));

    运行结果如下:

bogon:TestPhp$ php another_test_class.php 
string(4) "Base"
bool(true)
bool(true)
bool(false)
bool(false)
bool(true)

免责声明:文章转载自《PHP类和对象函数实例详解》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇C# 使用SkinSharp皮肤库mysql 创建表 create table详解下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Fody,告别烦人的INotifyPropertyChanged,最简方式实现通知!

INotifyPropertyChanged 我不是针对谁,我是说在座的各位 相信所有学wpf的,都写过类似下面的代码: 实现INotifyPropertyChanged public class MainViewModel : INotifyPropertyChanged { public event PropertyChangedEventHa...

Ubuntu下lamp(PHP+Mysql+Apache)搭建+完全卸载卸载方法

安装apache2 sudo apt-get install apache2 安装完成,运行如下命令重启下: sudo /etc/init.d/apache2 restart 在浏览器里输入http://localhost或者是http://127.0.0.1,如果看到了“It works!“,那就说明Apache就成功的安装了,Apache的默认安装,会...

PHP 之mysql空字符串问题

有一张user表如下所示:字段name不能为空。 CREATE TABLE `user` ( `id` int(11) NOT NULLAUTO_INCREMENT, `name` char(20) NOT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY(`id`) ) ENGINE=MyISAM DE...

httpclient个人理解

httpclient:模拟浏览器发送请求,服务器会响应数据,用心区域网内 不同系统间的请求调用 依赖  httpclient.jar和httpcore.jar需要同时纯在 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifac...

Android占位符

<xliff:g>标签介绍:属性id可以随便命名属性值举例说明%n$ms:代表输出的是字符串,n代表是第几个参数,设置m的值可以在输出之前放置空格%n$md:代表输出的是整数,n代表是第几个参数,设置m的值可以在输出之前放置空格,也可以设为0m,在输出之前放置m个0%n$mf:代表输出的是浮点数,n代表是第几个参数,设置m的值可以控制小数位数,...

php数据类型存储memcache探讨

一、标量类型:整型 浮动型 布尔 字符串 // 实例化一个memcache的类 $mem = new Memcache(); // 连接memcache的服务器 $mem->connect('localhost', 11211); // 设置数据 $mem->set('int',100,0,3600); $mem->set('float'...