首页 php教程 php手册 PHP面向对象中的重要知识点(三)

PHP面向对象中的重要知识点(三)

Jun 21, 2016 am 08:48 AM
nbsp php quot test

1. namespace:

 

    和C++中的名字空间很像,作用也一样,都是为了避免在引用较多第三方库时而带来的名字冲突问题。通过名字空间,即便两个class的名称相同,但是因为位于不同的名字空间内,他们仍然可以被精确定位和区分。第一次看到PHP的名字空间语法时,感觉和C++相比在语法上是非常非常相似的,然而在写点儿小例子做做实验的时候才发现,他们的差别还是很大的,为了避免以后忘记,所以这里特别将其记录了下来。见如下代码:

 

复制代码

//in Test2.php

namespace nstest\test2;

 

class Test2 {

    public static function printMe() {

        print 'This is nstest\test2\Test2::printSelf.'."\n";

    }

}

 

//in Test1.php

namespace nstest\test1;

 

class Test1 {

    public static function printMe() {

        print 'This is nstest\test1\Test1::printSelf.'."\n";

    }

}

require "Test2.php";

nstest\test2\Test2::printMe();

复制代码

    运行结果如下:

 

bogon:TestPhp$ php Test1.php 

PHP Fatal error:  Class 'nstest\test1\nstest\test2\Test2' not found in /Users/liulei/PhpstormProjects/TestPhp/Test1.php on line 13

    是不是这个结果比较出乎意料,原因在哪呢?HOHO,原来PHP在进行名字空间引用的时候,如果名字空间的第一个字符不是前导斜杠(\),那么就被自动识别为相对名字空间,在上面的代码中,Test1自身所在的名字空间是namespace nstest\test1,因此在以nstest\test2\Test2::printMe()方式调用Test2::printMe()时,PHP将自动解析为nstest\test1\nstest\test2\Test2::printMe(),即认为nstest\test2是在当前名字空间内部的。修正该问题非常简单,只需在引用时加上前导斜杠(\)即可,见以下修复后的代码:     

 

复制代码

//Test2.php

namespace nstest\test2;

 

class Test2 {

    public static function printMe() {

        print 'This is nstest\test2\Test2::printSelf.'."\n";

    }

}

 

//Test1.php

namespace nstest\test1;

 

class Test1 {

    public static function printMe() {

        print 'This is nstest\test1\Test1::printSelf.'."\n";

    }

}

require "Test2.php";

\nstest\test2\Test2::printMe();

复制代码

    运行结果如下:

 

bogon:TestPhp$ php Test1.php 

This is nstest\test2\Test2::printSelf.

    还有一种改动方式,可以示意一下PHP中名字空间中的相对引用。这里我们可以将Test1的名字空间改为namespace nstest,其他的修改见以下代码中红色高亮部分:

 

复制代码

//Test2.php

namespace nstest\test2;

 

class Test2 {

    public static function printMe() {

        print 'This is nstest\test2\Test2::printSelf.'."\n";

    }

}

 

//Test1.php

namespace nstest;

 

class Test1 {

    public static function printMe() {

        print 'This is nstest\test1\Test1::printSelf.'."\n";

    }

}

 

require "Test2.php";

test2\Test2::printMe(); 

复制代码

    运行结果等于上面正确的结果。最重要的差别就是该例使用了PHP名字空间中的相对定位。相信熟悉C++的开发者一定会想到use关键字,PHP也提供了该关键字,他们的功能是一致的,都是为了避免在后面的代码中,无需再通过全限定符(类名前加名字空间前缀)来引用其他名字空间中的类了。至于具体的语法规则,还是看看下面具体的代码和关键性注释吧。

 

复制代码

//Test2.php

namespace nstest\test2;

 

class Test2 {

    public static function printMe() {

        print 'This is nstest\test2\Test2::printSelf.'."\n";

    }

}

 

//Test1.php

namespace nstest\test1;

 

class Test1 {

    public static function printMe() {

        print 'This is nstest\test1\Test1::printSelf.'."\n";

    }

}

 

require "Test2.php";

//这里需要特别注意的是,nstest\test2已经表示名字空间绝对路径定位,不需要再加前导斜杠(\)了。

//另外这里还有一个隐式规则是test2表示该名字空间的缺省别名,在引用其名字空间内的对象时需要加test2前缀。

use nstest\test2;

test2\Test2::printMe();

 

//这里我们也可以给名字空间显式的指定别名,如:

use nstest\test2 as test2_alias;

test2_alias\Test2::printMe(); 

复制代码

    运行结果如下:

 

bogon:TestPhp$ php Test1.php 

This is nstest\test2\Test2::printSelf.

This is nstest\test2\Test2::printSelf.

    最后介绍一下PHP中全局名字空间的引用方式,见如下代码和关键性注释:

 

复制代码

class Test {

    public static function printMe() {

        print 'This is Global namespace Test::printSelf.'."\n";

    }

}

 

//下面两行代码表示的是同一对象,即全局名字空间下的Test类,然而如果因为名字空间冲突导致第一种方式不能被PHP

//编译器正常识别,那么就可以使用第二种方式显式的通知PHP,自己要引用的是全局名字空间中的Test类。

Test::printMe();

\Test::printMe();

复制代码

    运行结果如下:

 

bogon:TestPhp$ php Test1.php 

This is Global namespace Test::printSelf.

This is Global namespace Test::printSelf.

2. Reflection:

 

    PHP中的反射和Java中java.lang.reflect包提供的功能一样,更有意思的是,就连很多方法命名和调用方式也是非常雷同的。他们都是由一些列可以分析类、类方法和方法参数的PHP内置类组成。我们这里主要介绍的是如下几个常用的内置类:(Reflection、RelectionClass、ReflectionMethod、ReflectionParameter和ReflectionProperty)。现在我们还是一步一步来理解,即从ReflectionClass开始给出示例代码和关键性注释: 

 

复制代码

class TestClass {

    public $publicVariable;

 

    function publicMethod() {

        print "This is publicMethod.\n";

    }

}

 

function classInfo(ReflectionClass $c) {

    $details = "";

    //getName将返回实际的类名。

    $name = $c->getName();

    if ($c->isUserDefined()) {

        $details .= "$name is user defined.\n";

    }

    if ($c->isInternal()) {

        $details .= "$name is built-in.\n";

    }

    if ($c->isAbstract()) {

        $details .= "$name is abstract class.\n";

    }

    if ($c->isFinal()) {

        $details .= "$name is final class.\n";

    }

    if ($c->isInstantiable()) {

        $details .= "$name can be instantiated.\n";

    } else {

        $details .= "$name cannot be instantiated.\n";

    }

    return $details;

}

 

function classSource(ReflectionClass $c) {

    $path = $c->getFileName();

    $lines = @file($path);

    //获取类定义代码的起始行和截至行。

    $from = $c->getStartLine();

    $to = $c->getEndLine();

    $len = $to - $from + 1;

    return implode(array_slice($lines,$from - 1,$len));

}

 

print "The following is Class Information.\n";

print classInfo(new ReflectionClass('TestClass'));

 

print "\nThe following is Class Source.\n";

print classSource(new ReflectionClass('TestClass'));

复制代码

    运行结果如下:

 

复制代码

bogon:TestPhp$ php reflection_test.php 

The following is Class Information.

TestClass is user defined.

TestClass can be instantiated.

 

The following is Class Source.

class TestClass {

    public $publicVariable;

 

    function publicMethod() {

        print "This is publicMethod.\n";

    }

}

复制代码

    下面让我们仍然以代码示例和关键性注释的方法继续ReflectionMethod的学习之旅。

 

复制代码

class TestClass {

    public $publicVariable;

 

    function __construct() {

 

    }

    private function privateMethod() {

 

    }

    function publicMethod() {

        print "This is publicMethod.\n";

    }

    function publicMethod2(string $arg1, int $arg2) {

 

    }

}

 

//这个函数中使用的ReflectionMethod中的方法都是非常简单直观的,就不再过多赘述了。

function methodInfo(ReflectionMethod $m) {

    $name = $m->getName();

    $details = "";

    if ($m->isUserDefined()) {

        $details .= "$name is user defined.\n";

    }

    if ($m->isInternal()) {

        $details .= "$name is built-in.\n";

    }

    if ($m->isAbstract()) {

        $details .= "$name is abstract.\n";

    }

    if ($m->isPublic()) {

        $details .= "$name is public.\n";

    }

    if ($m->isProtected()) {

        $details .= "$name is protected.\n";

    }

    if ($m->isPrivate()) {

        $details .= "$name is private.\n";

    }

    if ($m->isStatic()) {

        $details .= "$name is static.\n";

    }

    if ($m->isFinal()) {

        $details .= "$name is final.\n";

    }

    if ($m->isConstructor()) {

        $details .= "$name is constructor.\n";

    }

    if ($m->returnsReference()) {

        $details .= "$name returns a reference.\n";

    }

    return $details;

}

 

function methodSource(ReflectionMethod $m) {

    $path = $m->getFileName();

    $lines = @file($path);

    $from = $m->getStartLine();

    $to = $m->getEndLine();

    $len = $to - $from + 1;

    return implode(array_slice($lines, $from - 1, $len));

}

 

$rc = new ReflectionClass('TestClass');

$methods = $rc->getMethods();

print "The following is method information.\n";

foreach ($methods as $method) {

    print methodInfo($method);

    print "\n--------------------\n";

}

 

print "The following is Method[TestClass::publicMethod] source.\n";

print methodSource($rc->getMethod('publicMethod'));

复制代码

    运行结果如下:

 

复制代码

bogon:TestPhp$ php reflection_test.php 

The following is method information.

__construct is user defined.

__construct is public.

__construct is constructor.

 

--------------------

privateMethod is user defined.

privateMethod is private.

 

--------------------

publicMethod is user defined.

publicMethod is public.

 

--------------------

publicMethod2 is user defined.

publicMethod2 is public.

 

--------------------

The following is Method[TestClass::publicMethod] source.

    function publicMethod() {

        print "This is publicMethod.\n";

    }

复制代码

    让我们继续ReflectionParameter吧,他表示的是成员函数的参数信息。继续看代码吧。

 

复制代码

class ParamClass {

 

}

 

class TestClass {

    function publicMethod() {

        print "This is publicMethod.\n";

    }

    function publicMethod2(ParamClass $arg1, &$arg2, $arg3 = null) {

 

    }

}

 

function paramInfo(ReflectionParameter $p) {

    $details = "";

    //这里的$declaringClass将等于TestClass。

    $declaringClass = $p->getDeclaringClass();

    $name = $p->getName();

    $class = $p->getClass();

    $position = $p->getPosition();

    $details .= "\$$name has position $position.\n";

    if (!empty($class)) {

        $classname = $class->getName();

        $details .= "\$$name must be a $classname object\n";

    }

    if ($p->isPassedByReference()) {

        $details .= "\$$name is passed by reference.\n";

    }

    if ($p->isDefaultValueAvailable()) {

        $def = $p->getDefaultValue();

        $details .= "\$$name has default: $def\n";

    }

    return $details;

}

 

$rc = new ReflectionClass('TestClass');

$method = $rc->getMethod('publicMethod2');

$params = $method->getParameters();

 

foreach ($params as $p) {

    print paramInfo($p)."\n";

}

复制代码

    运行结果如下:

 

复制代码

bogon:TestPhp$ php reflection_test.php 

$arg1 has position 0.

$arg1 must be a ParamClass object

 

$arg2 has position 1.

$arg2 is passed by reference.

 

$arg3 has position 2.

$arg3 has default: 

复制代码

    上面介绍的都是通过PHP提供的Reflection API来遍历任意class的具体信息,事实上和Java等其他语言提供的反射功能一样,PHP也同样支持通过反射类调用实际对象的方法,这里将主要应用到两个方法,分别是ReflectionClass::newInstance()来创建对象实例,另一个是ReflectionMethod::invoke(),根据对象实例和方法名执行该方法。见如下代码:

 

复制代码

class TestClass {

    private $privateArg;

    function __construct($arg) {

        $this->privateArg = $arg;

    }

    function publicMethod() {

        print '$privateArg = '.$this->privateArg."\n";

    }

 

    function publicMethod2($arg1, $arg2) {

        print '$arg1 = '.$arg1.' $arg2 = '.$arg2."\n";

    }

}

 

$rc = new ReflectionClass('TestClass');

$testObj = $rc->newInstanceArgs(array('This is private argument.'));

$method = $rc->getMethod('publicMethod');

$method->invoke($testObj);

 

$method2 = $rc->getMethod('publicMethod2');

$method2->invoke($testObj,"hello","world");

复制代码

    运行结果如下:

 

bogon:TestPhp$ php reflection_test.php 

$privateArg = This is private argument.

$arg1 = hello $arg2 = world

    事实上ReflectionClass、ReflectionMethod和ReflectionParameter提供给我们的可用方法还有更多,这里只是给出几个最典型的方法,以便我们可以更为直观的学习和了解PHP Reflection API。相信再看完以后的代码示例之后,我们都会比较清楚,如果今后需要用到和class相关的功能,就从ReflectionClass中查找,而member function的信息则一定来自于ReflectionMethod,方法参数信息来自于ReflectionParameter。

 

注:该Blog中记录的知识点,是在我学习PHP的过程中,遇到的一些PHP和其他面向对象语言相比比较独特的地方,或者是对我本人而言确实需要簿记下来以备后查的知识点。虽然谈不上什么深度,但是还是希望能与大家分享。



本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系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)

热门话题

Java教程
1664
14
CakePHP 教程
1422
52
Laravel 教程
1316
25
PHP教程
1267
29
C# 教程
1239
24
在PHP API中说明JSON Web令牌(JWT)及其用例。 在PHP API中说明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一种基于JSON的开放标准,用于在各方之间安全地传输信息,主要用于身份验证和信息交换。1.JWT由Header、Payload和Signature三部分组成。2.JWT的工作原理包括生成JWT、验证JWT和解析Payload三个步骤。3.在PHP中使用JWT进行身份验证时,可以生成和验证JWT,并在高级用法中包含用户角色和权限信息。4.常见错误包括签名验证失败、令牌过期和Payload过大,调试技巧包括使用调试工具和日志记录。5.性能优化和最佳实践包括使用合适的签名算法、合理设置有效期、

解释PHP中的晚期静态绑定(静态::)。 解释PHP中的晚期静态绑定(静态::)。 Apr 03, 2025 am 12:04 AM

静态绑定(static::)在PHP中实现晚期静态绑定(LSB),允许在静态上下文中引用调用类而非定义类。1)解析过程在运行时进行,2)在继承关系中向上查找调用类,3)可能带来性能开销。

php程序在字符串中计数元音 php程序在字符串中计数元音 Feb 07, 2025 pm 12:12 PM

字符串是由字符组成的序列,包括字母、数字和符号。本教程将学习如何使用不同的方法在PHP中计算给定字符串中元音的数量。英语中的元音是a、e、i、o、u,它们可以是大写或小写。 什么是元音? 元音是代表特定语音的字母字符。英语中共有五个元音,包括大写和小写: a, e, i, o, u 示例 1 输入:字符串 = "Tutorialspoint" 输出:6 解释 字符串 "Tutorialspoint" 中的元音是 u、o、i、a、o、i。总共有 6 个元

什么是PHP魔术方法(__ -construct,__destruct,__call,__get,__ set等)并提供用例? 什么是PHP魔术方法(__ -construct,__destruct,__call,__get,__ set等)并提供用例? Apr 03, 2025 am 12:03 AM

PHP的魔法方法有哪些?PHP的魔法方法包括:1.\_\_construct,用于初始化对象;2.\_\_destruct,用于清理资源;3.\_\_call,处理不存在的方法调用;4.\_\_get,实现动态属性访问;5.\_\_set,实现动态属性设置。这些方法在特定情况下自动调用,提升代码的灵活性和效率。

PHP和Python:比较两种流行的编程语言 PHP和Python:比较两种流行的编程语言 Apr 14, 2025 am 12:13 AM

PHP和Python各有优势,选择依据项目需求。1.PHP适合web开发,尤其快速开发和维护网站。2.Python适用于数据科学、机器学习和人工智能,语法简洁,适合初学者。

PHP行动:现实世界中的示例和应用程序 PHP行动:现实世界中的示例和应用程序 Apr 14, 2025 am 12:19 AM

PHP在电子商务、内容管理系统和API开发中广泛应用。1)电子商务:用于购物车功能和支付处理。2)内容管理系统:用于动态内容生成和用户管理。3)API开发:用于RESTfulAPI开发和API安全性。通过性能优化和最佳实践,PHP应用的效率和可维护性得以提升。

PHP:网络开发的关键语言 PHP:网络开发的关键语言 Apr 13, 2025 am 12:08 AM

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

说明匹配表达式(PHP 8)及其与开关的不同。 说明匹配表达式(PHP 8)及其与开关的不同。 Apr 06, 2025 am 12:03 AM

在PHP8 中,match表达式是一种新的控制结构,用于根据表达式的值返回不同的结果。1)它类似于switch语句,但返回值而非执行语句块。2)match表达式使用严格比较(===),提升了安全性。3)它避免了switch语句中可能的break遗漏问题,增强了代码的简洁性和可读性。

See all articles