PHP類和物件函式例項詳解

OrangeAdmin發表於2014-01-06

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.
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.\n";
    }
}

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.....................\n";
    foreach ($items as $key => $value) {
        print '$key = '.$key. ' => $value = '.$value."\n";
    }
}

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.\n";
$testObj->publicFunction();

print "\nThe following is output out of TestClass.\n";
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)

相關文章