PHP面向对象中的重要知识点(三)
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和其他面向对象语言相比比较独特的地方,或者是对我本人而言确实需要簿记下来以备后查的知识点。虽然谈不上什么深度,但是还是希望能与大家分享。

핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

JWT는 주로 신분증 인증 및 정보 교환을 위해 당사자간에 정보를 안전하게 전송하는 데 사용되는 JSON을 기반으로 한 개방형 표준입니다. 1. JWT는 헤더, 페이로드 및 서명의 세 부분으로 구성됩니다. 2. JWT의 작업 원칙에는 세 가지 단계가 포함됩니다. JWT 생성, JWT 확인 및 Parsing Payload. 3. PHP에서 인증에 JWT를 사용하면 JWT를 생성하고 확인할 수 있으며 사용자 역할 및 권한 정보가 고급 사용에 포함될 수 있습니다. 4. 일반적인 오류에는 서명 검증 실패, 토큰 만료 및 대형 페이로드가 포함됩니다. 디버깅 기술에는 디버깅 도구 및 로깅 사용이 포함됩니다. 5. 성능 최적화 및 모범 사례에는 적절한 시그니처 알고리즘 사용, 타당성 기간 설정 합리적,

정적 바인딩 (정적 : :)는 PHP에서 늦은 정적 바인딩 (LSB)을 구현하여 클래스를 정의하는 대신 정적 컨텍스트에서 호출 클래스를 참조 할 수 있습니다. 1) 구문 분석 프로세스는 런타임에 수행됩니다. 2) 상속 관계에서 통화 클래스를 찾아보십시오. 3) 성능 오버 헤드를 가져올 수 있습니다.

문자열은 문자, 숫자 및 기호를 포함하여 일련의 문자입니다. 이 튜토리얼은 다른 방법을 사용하여 PHP의 주어진 문자열의 모음 수를 계산하는 방법을 배웁니다. 영어의 모음은 A, E, I, O, U이며 대문자 또는 소문자 일 수 있습니다. 모음이란 무엇입니까? 모음은 특정 발음을 나타내는 알파벳 문자입니다. 대문자와 소문자를 포함하여 영어에는 5 개의 모음이 있습니다. a, e, i, o, u 예 1 입력 : String = "Tutorialspoint" 출력 : 6 설명하다 문자열의 "Tutorialspoint"의 모음은 u, o, i, a, o, i입니다. 총 6 개의 위안이 있습니다

PHP의 마법 방법은 무엇입니까? PHP의 마법 방법은 다음과 같습니다. 1. \ _ \ _ Construct, 객체를 초기화하는 데 사용됩니다. 2. \ _ \ _ 파괴, 자원을 정리하는 데 사용됩니다. 3. \ _ \ _ 호출, 존재하지 않는 메소드 호출을 처리하십시오. 4. \ _ \ _ get, 동적 속성 액세스를 구현하십시오. 5. \ _ \ _ Set, 동적 속성 설정을 구현하십시오. 이러한 방법은 특정 상황에서 자동으로 호출되어 코드 유연성과 효율성을 향상시킵니다.

PHP와 Python은 각각 고유 한 장점이 있으며 프로젝트 요구 사항에 따라 선택합니다. 1.PHP는 웹 개발, 특히 웹 사이트의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 간결한 구문을 가진 데이터 과학, 기계 학습 및 인공 지능에 적합하며 초보자에게 적합합니다.

PHP는 전자 상거래, 컨텐츠 관리 시스템 및 API 개발에 널리 사용됩니다. 1) 전자 상거래 : 쇼핑 카트 기능 및 지불 처리에 사용됩니다. 2) 컨텐츠 관리 시스템 : 동적 컨텐츠 생성 및 사용자 관리에 사용됩니다. 3) API 개발 : 편안한 API 개발 및 API 보안에 사용됩니다. 성능 최적화 및 모범 사례를 통해 PHP 애플리케이션의 효율성과 유지 보수 성이 향상됩니다.

PHP는 서버 측에서 널리 사용되는 스크립팅 언어이며 특히 웹 개발에 적합합니다. 1.PHP는 HTML을 포함하고 HTTP 요청 및 응답을 처리 할 수 있으며 다양한 데이터베이스를 지원할 수 있습니다. 2.PHP는 강력한 커뮤니티 지원 및 오픈 소스 리소스를 통해 동적 웹 컨텐츠, 프로세스 양식 데이터, 액세스 데이터베이스 등을 생성하는 데 사용됩니다. 3. PHP는 해석 된 언어이며, 실행 프로세스에는 어휘 분석, 문법 분석, 편집 및 실행이 포함됩니다. 4. PHP는 사용자 등록 시스템과 같은 고급 응용 프로그램을 위해 MySQL과 결합 할 수 있습니다. 5. PHP를 디버깅 할 때 error_reporting () 및 var_dump ()와 같은 함수를 사용할 수 있습니다. 6. 캐싱 메커니즘을 사용하여 PHP 코드를 최적화하고 데이터베이스 쿼리를 최적화하며 내장 기능을 사용하십시오. 7
