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

相关文章

使用DeepSeek API 结合VSCode提升开发效率

《使用DeepSeekAPI结合VSCode提升开发效率》:本文主要介绍DeepSeekAPI与VisualStudioCode(VSCode)结合使用,以提升软件开发效率,具有一定的参考价值... 目录引言准备工作安装必要的 VSCode 扩展配置 DeepSeek API1. 创建 API 请求文件2.

使用TomCat,service输出台出现乱码的解决

《使用TomCat,service输出台出现乱码的解决》本文介绍了解决Tomcat服务输出台中文乱码问题的两种方法,第一种方法是修改`logging.properties`文件中的`prefix`和`... 目录使用TomCat,service输出台出现乱码问题1解决方案问题2解决方案总结使用TomCat,

解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题

《解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题》文章详细描述了在使用lombok的@Data注解标注实体类时遇到编译无误但运行时报错的问题,分析... 目录问题分析问题解决方案步骤一步骤二步骤三总结问题使用lombok注解@Data标注实体类,编译时

Java中使用Java Mail实现邮件服务功能示例

《Java中使用JavaMail实现邮件服务功能示例》:本文主要介绍Java中使用JavaMail实现邮件服务功能的相关资料,文章还提供了一个发送邮件的示例代码,包括创建参数类、邮件类和执行结... 目录前言一、历史背景二编程、pom依赖三、API说明(一)Session (会话)(二)Message编程客

C++中使用vector存储并遍历数据的基本步骤

《C++中使用vector存储并遍历数据的基本步骤》C++标准模板库(STL)提供了多种容器类型,包括顺序容器、关联容器、无序关联容器和容器适配器,每种容器都有其特定的用途和特性,:本文主要介绍C... 目录(1)容器及简要描述‌php顺序容器‌‌关联容器‌‌无序关联容器‌(基于哈希表):‌容器适配器‌:(

使用Python实现高效的端口扫描器

《使用Python实现高效的端口扫描器》在网络安全领域,端口扫描是一项基本而重要的技能,通过端口扫描,可以发现目标主机上开放的服务和端口,这对于安全评估、渗透测试等有着不可忽视的作用,本文将介绍如何使... 目录1. 端口扫描的基本原理2. 使用python实现端口扫描2.1 安装必要的库2.2 编写端口扫

使用Python实现操作mongodb详解

《使用Python实现操作mongodb详解》这篇文章主要为大家详细介绍了使用Python实现操作mongodb的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、示例二、常用指令三、遇到的问题一、示例from pymongo import MongoClientf

SQL Server使用SELECT INTO实现表备份的代码示例

《SQLServer使用SELECTINTO实现表备份的代码示例》在数据库管理过程中,有时我们需要对表进行备份,以防数据丢失或修改错误,在SQLServer中,可以使用SELECTINT... 在数据库管理过程中,有时我们需要对表进行备份,以防数据丢失或修改错误。在 SQL Server 中,可以使用 SE

使用Python合并 Excel单元格指定行列或单元格范围

《使用Python合并Excel单元格指定行列或单元格范围》合并Excel单元格是Excel数据处理和表格设计中的一项常用操作,本文将介绍如何通过Python合并Excel中的指定行列或单... 目录python Excel库安装Python合并Excel 中的指定行Python合并Excel 中的指定列P

浅析Rust多线程中如何安全的使用变量

《浅析Rust多线程中如何安全的使用变量》这篇文章主要为大家详细介绍了Rust如何在线程的闭包中安全的使用变量,包括共享变量和修改变量,文中的示例代码讲解详细,有需要的小伙伴可以参考下... 目录1. 向线程传递变量2. 多线程共享变量引用3. 多线程中修改变量4. 总结在Rust语言中,一个既引人入胜又可