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 请问各位,如何在Jetson nano主控板的Ubuntu系统中安装PyQt5
  • ¥15 MAC安装佳能LBP2900驱动的网盘提取码
  • ¥400 微信停车小程序谁懂的来
  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败
  • ¥20 GZ::CTF如何兼容一些靶机?
  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位
  • ¥15 为何重叠加权后love图的SMD与svyCreateTableOne函数绘制基线表的不一致
  • ¥150 求 《小魔指》街机游戏机整合模拟软件