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.

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!