【问题标题】:How can I connect php files from different folders in php?如何在 php 中连接不同文件夹中的 php 文件?
【发布时间】:2023-03-21 19:12:01
【问题描述】:

你能帮我连接不同文件夹中的 php 文件吗..

我有一个主文件夹示例,然后在其中我有 2 个文件夹,分别命名为 0libPortal

在文件夹0lib 里面有文件夹amazon,里面有文件夹MockModelSamples 和一些php 文件,比如Client.phpModel.php

Portal文件夹内我有productFeed.php

我已经使用include()require() 连接了这些文件。我也使用自动加载类...它们看起来不错,但是当我运行它时,错误说...

致命错误:在第 68 行的 /var/www/html/sample/0lib/amazon/Samples/SubmitFeedSample.php 中找不到类“amazon_Client”

SubmitFeedSample.php 位于文件夹 0lib->amazon->Samples->SubmitFeedSample.php

这是我的自动加载类代码:

 function __autoload($className){
    $filePath = str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
    $includePaths = explode(PATH_SEPARATOR, get_include_path());
    foreach($includePaths as $includePath){
        if(file_exists($includePath . DIRECTORY_SEPARATOR . $filePath)){
            require_once $filePath;
            return;
        }
    }
}

我认为自动加载是这里的问题。

【问题讨论】:

  • 所以您有一个名为amazon_Client 的类,并且您正尝试使用spl_autoload_register() 使其在amazon 文件夹中自动加载Client.php
  • 是的先生,这正是我正在做的......

标签: php amazon-web-services


【解决方案1】:

通过进行一项更改,我让您的功能按原样工作:

function __autoload($className){
    $filePath = str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
    $includePaths = explode(PATH_SEPARATOR, get_include_path());
    foreach($includePaths as $includePath){
        // Assign the compiled file path here
        if(file_exists($classdir = $includePath . DIRECTORY_SEPARATOR . $filePath)){
            // Don't use $filePath but rather newly assigned $classdir
            require_once($classdir);
            return;
        }
    }
}

编辑:

该功能有效,但我认为您缺少相对(或绝对)路径。尝试创建一个config.php 文件,您可以将其包含在所有将设置根路径的页面上:

root/config.php

define("ROOTDIR",__DIR__);
spl_autoload_register('__autoload');

root/some/document.php

include_once(__DIR__.'/../config.php');

$test = new test_Test();

function.__autoload()

function __autoload($className)
    {
        $filePath = str_replace('_',"/",$className).'.php';
        // This would yield something like:
        // /data/19/2/133/150/2948313/user/3268049/htdocs/mydomain/test/Test.php
        $classdir = ROOTDIR."/".$filePath;
        if(file_exists($classdir)) {
            require_once($classdir);
            return;
        }
    }

test_Test 类:

这个类需要在这里:ROOTDIR.'/test/Test.php'

【讨论】:

  • 好的先生,我试试这个..:)
  • 您应该回显$classdir 并查看该路径是什么。
  • 你的代码确实有效,我在我的系统上试过了,它包含了文件。话虽如此,运行文件与类所在的文件夹位于同一目录中。
  • 路径是amazon/Client.php
  • 仅此而已?它应该包括完整的包含路径,例如:/data/some/thing/user/123123/htdocs/amazon/Client.php,因为您使用的是get_include_path() 函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
  • 1970-01-01
  • 2013-04-09
相关资源
最近更新 更多