Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用php自动加载Ajax文件的组织_Php_Ajax_Autoload_Organization - Fatal编程技术网

使用php自动加载Ajax文件的组织

使用php自动加载Ajax文件的组织,php,ajax,autoload,organization,Php,Ajax,Autoload,Organization,我想在我的php项目中使用autoloader,但我不知道我的文件组织是否可行。现在,我的文件夹的结构如下: -ProjectFolder index.php -common -ajax ajax_file.php -classes MyClass.php 在MyClass.php中,我有下面一行代码namespace common\classes 在index.php中,我有 spl_autoload_register(

我想在我的php项目中使用autoloader,但我不知道我的文件组织是否可行。现在,我的文件夹的结构如下:

-ProjectFolder
   index.php
   -common
      -ajax
         ajax_file.php
      -classes
         MyClass.php
在MyClass.php中,我有下面一行代码
namespace common\classes

在index.php中,我有

spl_autoload_register(function ($class_name){
  $file = str_replace('\\', '/', $class_name);
  require "$file.php";
});
因此,我可以在index.php文件中调用“test”静态方法,方法是在代码中包含以下行:
common\classes\MyClass::test()

但是index.php用于从ajax_file.php获取答案。 如果我只是通过将同一行代码添加到ajax_file.php中来调用我的“test”方法,它会告诉我找不到该类。我想这是因为它是独立于index.php中发生的事情加载的

我不知道如何从ajax_file.php访问MyClass,我甚至不确定这是否可能,因为我读过一些东西,似乎表明使用“./”自动加载器“返回”是不可能的


你能告诉我这样做的好方法是什么吗?

你必须确保你的自动加载器使用绝对路径而不是相对路径。 这涉及到为根命名空间定义一个基本目录,对应于
projectFolder

在index.php中:

spl\u自动加载寄存器(函数($class\u名称){
$file=\uuuu DIR\uuu.'/'.str\u replace(“\\\”、“/”、$class\u name);
需要“$file.php”;
});
您有一些符合标准(PSR-4)的自动加载器示例


请注意,ajax_file.php文件必须明确包含自动加载器(因此index.php

谢谢,我按照您的说明操作,它可以正常工作。我将自动加载函数放在index.php和ajax_file.php中包含的另一个文件中。我要说的是,我不知道php如何识别哪个文件夹是这三个文件夹的根,也不知道他是如何找到MyClass.php文件的。