本文章的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";
}
else
print "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 29 Call Stack:
0.0008 131888 1. {main}() E:\phpStormWorks\php01\test\index.php:0
0.0042 147400 2. class_implements() E:\phpStormWorks\php01\test\index.php:29 NO,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 46 ReflectionException: Class ChildrenClass does not exist in E:\phpStormWorks\php01\test\index.php on line 46 Call Stack:
0.0008 131888 1. {main}() E:\phpStormWorks\php01\test\index.php:0
0.0079 147816 2. ReflectionClass->__construct() E:\phpStormWorks\php01\test\index.php:46 Process 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 class
print "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";
else
print "spl_autoload_ autoload:$className | $classId | is loaded\n";
} }
});

PHP spl_autoload和class_exsits使用技能的更多相关文章

  1. PHP autoload与spl_autoload自动加载机制的深入理解

    PHP autoload与spl_autoload自动加载机制的深入理解 作者: 字体:[增加 减小] 类型:转载 时间:2013-06-05我要评论 本篇文章是对PHP中的autoload与spl_ ...

  2. iOS使用技能 - 短信,语言验证码的获取与验证小结

    最近有学习一个小技能,这里小结一下,分享给大家,互相交流. 首先是大体步骤: 在mob官网注册,然后添加短信验证的应用 使用cocoapods导入框架 Podfile文件: platform :ios ...

  3. 第二章作业-第3题(markdown格式)-万世想

    第3题题目是: 完成小组的"四则运算"项目的需求文档(使用Markdown写文档),尝试同组成员在各自PC上修改同一文档后,如何使用Git命令完成GitHub上的文档的更新,而不产 ...

  4. php 设计模式--准备篇

    要了解设计模式 首先我们要先了解 php的命名空间和类的自动载入的功能 下面我们来说一下 命名空间 概念缘由:比如一个a.php的文章 但是我们需要两个 此时同一个目录下不可能存在两个a.php 那么 ...

  5. Beta阶段测试报告

    前端测试计划 具体测试项如下: 注册测试 登录测试 忘记密码测试 一次登录后自动登录测试 退出登录测试 编辑资料测试 查看好友测试 搜索好友测试 添加好友测试 获取当前正在游戏的房间测试 创建房间测试 ...

  6. C#事件的理解应用

    之前对C#的事件理解的不够透彻,总是感觉在实际应用上差一些火候.最近写character类的相关内容,有了一些理解,在这里分享一下. &感觉大神没必要往下看了 下面开始正式内容: 比如说,角色 ...

  7. PHP7函数大全(4553个函数)

    转载来自: http://www.infocool.net/kb/PHP/201607/168683.html a 函数 说明 abs 绝对值 acos 反余弦 acosh 反双曲余弦 addcsla ...

  8. 【CQgame】[幸运方块 v1.1.2] [Lucky_Block v1.1.2]

    搬家首发!!! 其实从初一我就写过一些小型战斗的游戏,但是画面都太粗糙,代码也比较乱,也就是和两三个同学瞎玩,但自从观摩了PoPoQQQ大神的游戏,顿时产生了重新写一部游戏的冲动,于是各种上网查找各种 ...

  9. PHP5各个版本的新功能和新特性总结

    因为 PHP 那“集百家之长”的蛋疼语法,加上社区氛围不好,很多人对新版本,新特征并无兴趣.本文将会介绍自 PHP5.2 起,直至 PHP5.6 中增加的新特征 本文目录:PHP5.2 以前:auto ...

随机推荐

  1. 11.Django基础九之中间件

    一 前戏 我们在前面的课程中已经学会了给视图函数加装饰器来判断是用户是否登录,把没有登录的用户请求跳转到登录页面.我们通过给几个特定视图函数加装饰器实现了这个需求.但是以后添加的视图函数可能也需要加上 ...

  2. 生产环境项目问题记录系列(二):Docker打包镜像Nuget包因权限问题还原失败

    docker打包镜像遇到一个因为nuget权限验证问题导致镜像打包失败的问题,公司Nuget包用的是tfs管理的,tfs有权限验证,结果导致nuget还原失败,原有的NuGet.config文件如下: ...

  3. .Net Core 商城微服务项目系列(六):搭建自己的Nuget包服务器

    当我们使用微服务架构之后,紧接而来的问题便是服务之间的程序集引用问题,可能没接触过的同学不太理解这句话,都已经微服务化了为什么还要互相引用程序集,当然可以不引用.但是我们会有这样一种情况,我们的每个接 ...

  4. mybatis执行过程及经典面试题

    Mybatis执行流程 mybatis中xml解析是通过SqlSessionFactoryBuilder.build()方法. 初始化mybatis(解析xml文件构建成Configuration对象 ...

  5. ELK 学习笔记之 elasticsearch启动时Warning解决办法

    elasticsearch启动时Warning解决办法: 转载:http://www.dajiangtai.com/community/18136.do?origin=csdn-geek&dt ...

  6. MongoDB 学习笔记之 索引选项和重建索引

    索引选项: {background:true}在后台创建索引,索引在构建过程中,其他客户端仍然可以查询数据,不会阻塞. db.comments.createIndex({anonymous: 1},{ ...

  7. Android的各大框架整理

    OpenDanmaku  :一个Android的弹幕控件 地址:https://github.com/linsea/OpenDanmaku AndroidViewAnimations:Andorid视 ...

  8. 利用JVM在线调试工具排查线上问题

    在生产上我们经常会碰到一些不好排查的问题,例如线程安全问题,用最简单的threaddump或者heapdump不好查到问题原因.为了排查这些问题,有时我们会临时加一些日志,比如在一些关键的函数里打印出 ...

  9. C# WinForm 跨线程访问控件(实用简洁写法)

    C# WinForm 跨线程访问控件(实用简洁写法) 1.<C# WinForm 跨线程访问控件(实用简洁写法)>       2.<基于.NET环境,C#语言 实现 TCP NAT ...

  10. Java8新特性时间日期库DateTime API及示例

    Java8新特性的功能已经更新了不少篇幅了,今天重点讲解时间日期库中DateTime相关处理.同样的,如果你现在依旧在项目中使用传统Date.Calendar和SimpleDateFormat等API ...