首頁 後端開發 php教程 PHP类和对象函数实例详解_PHP教程

PHP类和对象函数实例详解_PHP教程

Jul 13, 2016 am 10:41 AM
函數 實例 物件

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) 判断指定类或者对象中是否含有指定的成员变量。
 
//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";
    }
}
 
//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: 
 
    分别返回当前可以访问的所有类和接口,这不仅包括自定义类和接口,也包括了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) 获取可以访问的非静态成员变量。
 
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) 静态方法调用时当前的类名称。
 
 
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的子类。
 
 
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)

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/678024.htmlTechArticle1. interface_exists、class_exists、method_exists和property_exists: 顾名思义,从以上几个函数的命名便可以猜出几分他们的功能。我想这也是我随着对...
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

golang函數動態建立新函數的技巧 golang函數動態建立新函數的技巧 Apr 25, 2024 pm 02:39 PM

Go語言提供了兩種動態函數創建技術:closures和反射。 closures允許存取閉包作用域內的變量,而反射可使用FuncOf函數建立新函數。這些技術在自訂HTTP路由器、實現高度可自訂的系統和建置可插拔的元件方面非常有用。

C++ 函數命名中參數順序的考慮 C++ 函數命名中參數順序的考慮 Apr 24, 2024 pm 04:21 PM

在C++函數命名中,考慮參數順序至關重要,可提高可讀性、減少錯誤並促進重構。常見的參數順序約定包括:動作-物件、物件-動作、語意意義和遵循標準函式庫。最佳順序取決於函數目的、參數類型、潛在混淆和語言慣例。

excel函數公式大全 excel函數公式大全 May 07, 2024 pm 12:04 PM

1. SUM函數,用於對一列或一組單元格中的數字進行求和,例如:=SUM(A1:J10)。 2、AVERAGE函數,用於計算一列或一組儲存格中的數字的平均值,例如:=AVERAGE(A1:A10)。 3.COUNT函數,用於計算一列或一組單元格中的數字或文字的數量,例如:=COUNT(A1:A10)4、IF函數,用於根據指定的條件進行邏輯判斷,並返回相應的結果。

如何在Java中寫出高效和可維護的函數? 如何在Java中寫出高效和可維護的函數? Apr 24, 2024 am 11:33 AM

編寫高效且可維護的Java函數的關鍵在於:保持簡潔。使用有意義的命名。處理特殊情況。使用適當的可見性。

如何將 MySQL 查詢結果陣列轉換為物件? 如何將 MySQL 查詢結果陣列轉換為物件? Apr 29, 2024 pm 01:09 PM

將MySQL查詢結果陣列轉換為物件的方法如下:建立一個空物件陣列。循環結果數組並為每一行建立一個新的物件。使用foreach迴圈將每一行的鍵值對賦給新物件的對應屬性。將新物件加入到物件數組中。關閉資料庫連線。

C++ 函式預設參數與可變參數的優缺點比較 C++ 函式預設參數與可變參數的優缺點比較 Apr 21, 2024 am 10:21 AM

C++函數中預設參數的優點包括簡化呼叫、增強可讀性、避免錯誤。缺點是限制靈活性、命名限制。可變參數的優點包括無限彈性、動態綁定。缺點包括複雜性更高、隱式型別轉換、除錯困難。

C++ 函式回傳參考型別有什麼好處? C++ 函式回傳參考型別有什麼好處? Apr 20, 2024 pm 09:12 PM

C++中的函數傳回參考類型的好處包括:效能提升:引用傳遞避免了物件複製,從而節省了記憶體和時間。直接修改:呼叫方可以直接修改傳回的參考對象,而無需重新賦值。程式碼簡潔:引用傳遞簡化了程式碼,無需額外的賦值操作。

自訂 PHP 函數和預定義函數之間有什麼區別? 自訂 PHP 函數和預定義函數之間有什麼區別? Apr 22, 2024 pm 02:21 PM

自訂PHP函數與預定義函數的差異在於:作用域:自訂函數僅限於其定義範圍,而預定義函數可在整個腳本中存取。定義方式:自訂函數使用function關鍵字定義,而預先定義函數則由PHP核心定義。參數傳遞:自訂函數接收參數,而預先定義函數可能不需要參數。擴充性:自訂函數可以根據需要創建,而預定義函數是內建的且無法修改。

See all articles