douheng8629 2018-02-10 17:02 采纳率: 100%
浏览 85
已采纳

缺省的spl_autoload_register()命名空间行为,index.php在root之外

With modern PHP, calling

spl_autoload_register();

allows you to instantiate new classes without having to specify REQUIRE, INCLUDE nor USE within your php files, as long as they have a namespace, and as long as that namespace follows a folder/file structure such as:

|--models
     |-- utility
|           |___calculator.php
|
|
|--index.php

With such setup, if calculator.php has declared on its top "namespace models\utility", and it contains the class Calculator (a match to the file name calculator.php) you can automatically instantiate it from index.php by calling:

calc = New models\utility\Calculator();

However, if the folder structure is like this:

|--models
     |-- utility
|           |___calculator.php
|
|
|--public
     |--index.php

Now index.php can no longer access calculator through its namespace, as index.php is no longer at the root folder.

It seems that there is no way for public/index.php to reach namespaces above its level. It is just a limitation of PHP. Is there a way perhaps to register a function with spl_autoload_register that would retain its automatic, easy to work with behavior but allowing index.php to instantiate namespaces above its folder level? Or another way to deal with this situation while still never having to USE nor REQUIRE/INCLUDE files?


UPDATE WITH ANSWER

This is a directory agnostic solution that worked for me. I can successfully instantiate new classes merely by calling their namespace, without having to resort on USE, REQUIRE nor INCLUDE even though index.php was moved to the /public folder.

//'/../../../../' points the autoloader.php file back to root directory
$include_path = realpath(dirname(__FILE__) . '/../../../../');         
set_include_path($include_path);
spl_autoload_register();
  • 写回答

1条回答 默认 最新

  • dosin84644 2018-02-10 17:17
    关注

    When the spl_autoload_register() function is called without the $autoload_function argument, the default autoloading function spl_autoload() is used.

    The spl_autoload() function checks all include paths for the file, matching namespaces to folders and class names to files as you have already noted.

    The key for you is to make sure that the folder containing the directory structure with your class files (i.e. the directory that contains models) is on the include path. This is commonly done using the set_include_path() function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题