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

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
使用數據庫存儲會話的優點是什麼?使用數據庫存儲會話的優點是什麼?Apr 24, 2025 am 12:16 AM

使用數據庫存儲會話的主要優勢包括持久性、可擴展性和安全性。 1.持久性:即使服務器重啟,會話數據也能保持不變。 2.可擴展性:適用於分佈式系統,確保會話數據在多服務器間同步。 3.安全性:數據庫提供加密存儲,保護敏感信息。

您如何在PHP中實現自定義會話處理?您如何在PHP中實現自定義會話處理?Apr 24, 2025 am 12:16 AM

在PHP中實現自定義會話處理可以通過實現SessionHandlerInterface接口來完成。具體步驟包括:1)創建實現SessionHandlerInterface的類,如CustomSessionHandler;2)重寫接口中的方法(如open,close,read,write,destroy,gc)來定義會話數據的生命週期和存儲方式;3)在PHP腳本中註冊自定義會話處理器並啟動會話。這樣可以將數據存儲在MySQL、Redis等介質中,提升性能、安全性和可擴展性。

什麼是會話ID?什麼是會話ID?Apr 24, 2025 am 12:13 AM

SessionID是網絡應用程序中用來跟踪用戶會話狀態的機制。 1.它是一個隨機生成的字符串,用於在用戶與服務器之間的多次交互中保持用戶的身份信息。 2.服務器生成並通過cookie或URL參數發送給客戶端,幫助在用戶的多次請求中識別和關聯這些請求。 3.生成通常使用隨機算法保證唯一性和不可預測性。 4.在實際開發中,可以使用內存數據庫如Redis來存儲session數據,提升性能和安全性。

您如何在無狀態環境(例如API)中處理會議?您如何在無狀態環境(例如API)中處理會議?Apr 24, 2025 am 12:12 AM

在無狀態環境如API中管理會話可以通過使用JWT或cookies來實現。 1.JWT適合無狀態和可擴展性,但大數據時體積大。 2.Cookies更傳統且易實現,但需謹慎配置以確保安全性。

您如何防止與會議有關的跨站點腳本(XSS)攻擊?您如何防止與會議有關的跨站點腳本(XSS)攻擊?Apr 23, 2025 am 12:16 AM

要保護應用免受與會話相關的XSS攻擊,需採取以下措施:1.設置HttpOnly和Secure標誌保護會話cookie。 2.對所有用戶輸入進行輸出編碼。 3.實施內容安全策略(CSP)限制腳本來源。通過這些策略,可以有效防護會話相關的XSS攻擊,確保用戶數據安全。

您如何優化PHP會話性能?您如何優化PHP會話性能?Apr 23, 2025 am 12:13 AM

优化PHP会话性能的方法包括:1.延迟会话启动,2.使用数据库存储会话,3.压缩会话数据,4.管理会话生命周期,5.实现会话共享。这些策略能显著提升应用在高并发环境下的效率。

什麼是session.gc_maxlifetime配置設置?什麼是session.gc_maxlifetime配置設置?Apr 23, 2025 am 12:10 AM

theSession.gc_maxlifetimesettinginphpdeterminesthelifespanofsessiondata,setInSeconds.1)它'sconfiguredinphp.iniorviaini_set().2)abalanceisesneededeededeedeedeededto toavoidperformance andunununununexpectedLogOgouts.3)

您如何在PHP中配置會話名?您如何在PHP中配置會話名?Apr 23, 2025 am 12:08 AM

在PHP中,可以使用session_name()函數配置會話名稱。具體步驟如下:1.使用session_name()函數設置會話名稱,例如session_name("my_session")。 2.在設置會話名稱後,調用session_start()啟動會話。配置會話名稱可以避免多應用間的會話數據衝突,並增強安全性,但需注意會話名稱的唯一性、安全性、長度和設置時機。

See all articles

熱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

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

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3 Mac版

SublimeText3 Mac版

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