PHP spl_autoload和class_exsits使用技能

2024-05-28 16:58

本文主要是介绍PHP spl_autoload和class_exsits使用技能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本文章的PHP使用版本:5.4.7

PHP建议使用:
spl_autoload_register
那么写了一种实现

文件路径

  • core
    • core.php
    • ChildrenClass.php
    • ParentClass.php
  • test
    • index.php

core.php:


<?php/*** Created by PhpStorm.* User: http://blog.csdn.net/cor_twi* Date: 2016/02/25* Time: 11:23*/spl_autoload_register(function ($classId)
{$dirname            = dirname(__FILE__);$classIdParts       = explode("\\", $classId);$classIdLength      = count($classIdParts);$className          = ($classIdParts[$classIdLength - 1]);$defaultNameSpace   = substr(strrchr($dirname,"\\"),1); $namespace          = $classIdLength==1? $defaultNameSpace : $classIdParts[0];for ($i = 1; $i < $classIdLength-1; $i++) {$namespace .= '/' . $classIdParts[$i];}$path = dirname(__FILE__) . "/../" . $namespace . "/" . $className . '.php';$realPath = realpath($path);#print "autoload:realPath:" .  $realPath."\n";if (file_exists($realPath)) {if(!class_exists($className,false)){$ret = include($realPath);print "spl_autoload_  autoload:$className is loaded : result = $ret \n";}elseprint "spl_autoload_ autoload:$className is already loaded\n";}
});

ChildrenClass.php:

<?php
namespace CORE;
use CORE\ParentClass;
/*** Created by PhpStorm.* User: http://blog.csdn.net/cor_twi* Date: 2016/02/22* Time: 9:55*/
class ChildrenClass extends ParentClass
{private $varPro_;public  function __construct($var01,$var02){parent::__construct($var01,$var02);$this->varPro_ = "ChildrenClass";}}

ParentClass.php:

<?php/*** Created by PhpStorm.* User: http://blog.csdn.net/cor_twi* Date: 2016/02/22* Time: 9:40*/
namespace CORE;
class ParentClass
{public static $variable01;public static $variable02;protected  $varPro;/***constructor*/public function __construct($var1,$var2){self::$variable01 = $var1;self::$variable02 = $var2;$this->varPro = "ParentClass";}
}

index.php:

<?php
/*** Created by PhpStorm.* User: http://blog.csdn.net/cor_twi* Date: 2016/03/05* Time: 16:06*/
require('../core/core.php');use CORE\ParentClass;
use CORE\ChildrenClass;print "Section01------------------------\n\n";print "\nSection02------------------------\n\n";$instance01 = new ChildrenClass('aa','vv');
$instance02 = new ParentClass('bb','uu');print "\nSection03------------------------\n\n";
print "Class Load Test-----------------------\n";if(!class_exists('ChildrenClass')){print "\n************\nWarning : in Section 03 : \nClass ChildrenClass is not loaded\n";
}$interfaces = class_implements("ParentClass");print_r($interfaces);
if(isset($interfaces['ParentClass'])){print "OK,PASS";
}
else{print "NO,IT'S NOT";
}print "\nSection04------------------------\n\n";
if(!class_exists('ChildrenClass')){print "\n************\nTEST : in Section 04 : \nClass ChildrenClass is not loaded\n";
}$rc =  new ReflectionClass('ChildrenClass');
try {if($rc->implementsInterface('ParentClass')){print 'imples';}print 'parent class:' . $rc->getParentClass();
}catch(ReflectionException $e){}

然后输出结果是:

J:\xampp\php\php.exe E:\phpStormWorks\php01\test\index.php
Section01------------------------Section02------------------------spl_autoload_  autoload:ParentClass is loaded : result = 1 
spl_autoload_  autoload:ChildrenClass is loaded : result = 1 Section03------------------------Class Load Test-----------------------************
Warning : in Section 03 : 
Class ChildrenClass is not loaded
spl_autoload_  autoload:ParentClass is loaded : result = 1 Warning: class_implements(): Class ParentClass does not exist and could not be loaded in E:\phpStormWorks\php01\test\index.php on line 29Call Stack:0.0008     131888   1. {main}() E:\phpStormWorks\php01\test\index.php:00.0042     147400   2. class_implements() E:\phpStormWorks\php01\test\index.php:29NO,IT'S NOT
Section04------------------------************
TEST : in Section 04 : 
Class ChildrenClass is not loaded
spl_autoload_  autoload:ChildrenClass is loaded : result = 1 Fatal error: Uncaught exception 'ReflectionException' with message 'Class ChildrenClass does not exist' in E:\phpStormWorks\php01\test\index.php on line 46ReflectionException: Class ChildrenClass does not exist in E:\phpStormWorks\php01\test\index.php on line 46Call Stack:0.0008     131888   1. {main}() E:\phpStormWorks\php01\test\index.php:00.0079     147816   2. ReflectionClass->__construct() E:\phpStormWorks\php01\test\index.php:46Process finished with exit code 255

总结:
class_implements()
ReflectionClass()
class_exists()
$interfaces = class_implements(‘\CORE\TestImpl’);
对于当前版本来说:
这几个类的名字必须写use 的短语 as 的也不行:
例如:class_exists(‘\CORE\ParentClass’)
$interfaces[‘CORE\Interf’]
namespace前面的\无所谓
但是interfaces[‘CORE\Interf’] 前面的\有所谓!!!

总结
对于写了namespace的类文件来说,你有两个选择
要么use namespace要么new 和 instanceof 的时候使用namespace,否则出现Fatal error: Class ‘TestImpl’ not found in 即便它正确触发spl_autoload。【原因见后面<Reason>】
要么用namespace前缀来使用这个类符号
如果没有写namespace的呢
没有写namespace的类文件,可以随意使用他的类名字,自动触发spl_autoload注册的函数。
对于类或者接口,class_exsits()和interface_exsits()都如果有他们有namespace需要使用它才能返回正确的结果。
对于class_implements()、ReflectionClass()和implementsInterface(),如果类或者接口具有namespace必须使用带namespace的名称符号来作为参数,否则你将看到:Fatal error: Cannot redeclare class NAMESPACE\XXXXClass in
原因未知:是个bug,经过测试PHP7也有这个问题PHP或许不承认他是个BUG。而且加载器无法检查出来已经被加载。如果你改成class_implements(‘XXXXClass’,false);那么就是[PHP 5.4.7]Warning: class_implements(): Class ChildrenClass does not exist in (即使你写了use)

PHP7:的报错是
PHP Fatal error: Cannot declare class CORE\ChildrenClass, because the name is already in use in E:\phpStormWorks\php01\core\ChildrenClass.php on line 29
PHP Stack trace:
PHP 1. {main}() E:\phpStormWorks\php01\test\index.php:0
PHP 2. class_implements() E:\phpStormWorks\php01\test\index.php:93
PHP 3. spl_autoload_call() E:\phpStormWorks\php01\test\index.php:93

<Reason>:由现象倒推而来,所有的PHP版本,对于有namespace的类或者接口,它是以 带namespace的形式autoload的,不管你写不写use

如果用include_once(),那么不在本文研究范围之内

写的时候手贱文章弄没有了一次,重写之。
测试结论仅供参考。
附上spl_autoload_实现:

<?php/*** Created by PhpStorm.* User: http://blog.csdn.net/cor_twi* Date: 2016/02/25* Time: 11:23*/spl_autoload_register(function ($classId)
{$dirname            = dirname(__FILE__);$classIdParts       = explode("\\", $classId);$classIdLength      = count($classIdParts);$className          = ($classIdParts[$classIdLength - 1]);$defaultNameSpace   = substr(strrchr($dirname,"\\"),1); //here is core$namespace          = $classIdLength==1? $defaultNameSpace : $classIdParts[0];for ($i = 1; $i < $classIdLength-1; $i++) {$namespace .= '/' . $classIdParts[$i];}$path = dirname(__FILE__) . "/../" . $namespace . "/" . $className . '.php';$realPath = realpath($path);#print "autoload:realPath:" .  $realPath."\n";if(class_exists($classId,false)||interface_exists($classId,false)){
//如果代码能进来这个函数说明没有被加载,便不会执行到这里,无法阻止Fatal error: Cannot redeclare classprint "spl_autoload_  preCheck:$className | $classId | is already loaded\n";}if (file_exists($realPath)) {if(class_exists($className,false)||interface_exists($className,false)){print "spl_autoload_  autoload:$className | $classId | is already loaded\n";}else{print "spl_autoload_  autoload: try to load $className | $classId |\n";if ( false ===  include($realPath))print "spl_autoload_  autoload:$className | $classId | failed to be loaded\n";elseprint "spl_autoload_  autoload:$className | $classId | is loaded\n";}}
});

这篇关于PHP spl_autoload和class_exsits使用技能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1011150

相关文章

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Java使用jar命令配置服务器端口的完整指南

《Java使用jar命令配置服务器端口的完整指南》本文将详细介绍如何使用java-jar命令启动应用,并重点讲解如何配置服务器端口,同时提供一个实用的Web工具来简化这一过程,希望对大家有所帮助... 目录1. Java Jar文件简介1.1 什么是Jar文件1.2 创建可执行Jar文件2. 使用java

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

PHP应用中处理限流和API节流的最佳实践

《PHP应用中处理限流和API节流的最佳实践》限流和API节流对于确保Web应用程序的可靠性、安全性和可扩展性至关重要,本文将详细介绍PHP应用中处理限流和API节流的最佳实践,下面就来和小编一起学习... 目录限流的重要性在 php 中实施限流的最佳实践使用集中式存储进行状态管理(如 Redis)采用滑动

Java中的抽象类与abstract 关键字使用详解

《Java中的抽象类与abstract关键字使用详解》:本文主要介绍Java中的抽象类与abstract关键字使用详解,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧... 目录一、抽象类的概念二、使用 abstract2.1 修饰类 => 抽象类2.2 修饰方法 => 抽象方法,没有