찾다
백엔드 개발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으로 문의하세요.
使用PHP的json_encode()函数将数组或对象转换为JSON字符串使用PHP的json_encode()函数将数组或对象转换为JSON字符串Nov 03, 2023 pm 03:30 PM

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式,已经成为Web应用程序之间数据交换的常用格式。PHP的json_encode()函数可以将数组或对象转换为JSON字符串。本文将介绍如何使用PHP的json_encode()函数,包括语法、参数、返回值以及具体的示例。语法json_encode()函数的语法如下:st

源码探秘:Python 中对象是如何被调用的?源码探秘:Python 中对象是如何被调用的?May 11, 2023 am 11:46 AM

楔子我们知道对象被创建,主要有两种方式,一种是通过Python/CAPI,另一种是通过调用类型对象。对于内置类型的实例对象而言,这两种方式都是支持的,比如列表,我们即可以通过[]创建,也可以通过list(),前者是Python/CAPI,后者是调用类型对象。但对于自定义类的实例对象而言,我们只能通过调用类型对象的方式来创建。而一个对象如果可以被调用,那么这个对象就是callable,否则就不是callable。而决定一个对象是不是callable,就取决于其对应的类型对象中是否定义了某个方法。如

使用Python的__contains__()函数定义对象的包含操作使用Python的__contains__()函数定义对象的包含操作Aug 22, 2023 pm 04:23 PM

使用Python的__contains__()函数定义对象的包含操作Python是一种简洁而强大的编程语言,提供了许多强大的功能来处理各种类型的数据。其中之一是通过定义__contains__()函数来实现对象的包含操作。本文将介绍如何使用__contains__()函数来定义对象的包含操作,并且给出一些示例代码。__contains__()函数是Pytho

使用Python的__le__()函数定义两个对象的小于等于比较使用Python的__le__()函数定义两个对象的小于等于比较Aug 21, 2023 pm 09:29 PM

标题:使用Python的__le__()函数定义两个对象的小于等于比较在Python中,我们可以通过使用特殊方法来定义对象之间的比较操作。其中之一就是__le__()函数,它用于定义小于等于比较。__le__()函数是Python中的一个魔法方法,并且是一种用于实现“小于等于”操作的特殊函数。当我们使用小于等于运算符(<=)比较两个对象时,Python

详解Javascript对象的5种循环遍历方法详解Javascript对象的5种循环遍历方法Aug 04, 2022 pm 05:28 PM

Javascript对象如何循环遍历?下面本篇文章给大家详细介绍5种JS对象遍历方法,并浅显对比一下这5种方法,希望对大家有所帮助!

Python中如何使用getattr()函数获取对象的属性值Python中如何使用getattr()函数获取对象的属性值Aug 22, 2023 pm 03:00 PM

Python中如何使用getattr()函数获取对象的属性值在Python编程中,我们经常会遇到需要获取对象属性值的情况。Python提供了一个内置函数getattr()来帮助我们实现这个目标。getattr()函数允许我们通过传递对象和属性名称作为参数来获取该对象的属性值。本文将详细介绍getattr()函数的用法,并提供实际的代码示例,以便更好地理解。g

使用Python的isinstance()函数判断对象是否属于某个类使用Python的isinstance()函数判断对象是否属于某个类Aug 22, 2023 am 11:52 AM

使用Python的isinstance()函数判断对象是否属于某个类在Python中,我们经常需要判断一个对象是否属于某个特定的类。为了方便地进行类别判断,Python提供了一个内置函数isinstance()。本文将介绍isinstance()函数的用法,并提供代码示例。isinstance()函数可以判断一个对象是否属于指定的类或类的派生类。它的语法如下

Vue中如何使用v-for指令循环输出对象Vue中如何使用v-for指令循环输出对象Jun 11, 2023 am 08:51 AM

在Vue中,v-for是一种指令,在模板中使用它可以对数组或对象进行循环操作。v-for指令用于循环渲染数据,它是Vue中非常有用的指令之一。在Vue中,使用v-for指令循环输出对象的方式和循环输出数组的方式类似,只需要稍作区别即可。如何使用v-for指令循环输出对象呢?下面我们将分以下几个部分进行讲解。一、v-for指令的基本使用v-for指令的基本语法

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.