PHP函数作用域失败


PHP Function Scope Failure

我正在努力理解作用域,以及是什么阻止了我的新代码工作(假设这是一个作用域问题)。

下面的函数在文件PATH.'/includes/custom-functions.php'中引用了一个类:

    function infusion() {
      require_once(PATH.'/classes/infusion.php'); //PATH is defined in WordPress from ~/wp-content/themes/theme/
      return new infusion();
    }

类依赖于PATH.'/api/isdk.php'/api/目录下另一个文件的连接凭据。在PATH .'/includes/custom-functions.php'内部,我有许多其他函数调用$infusion = infusion();并且工作完美。


我创建了一个新文件:PATH.'/includes/report.php',我需要访问$infusion = infusion();,但不能通过重复上面的function infusion()定义来工作;使用require_once();;或者使用include();。所有这三个选项都简单地杀死了剩下的代码,我只能得出结论——好吧,我没有结论。

我假设代码没有使用名称空间,因此不允许重新声明infusion函数(通过重新定义函数或重新包含类)。

您的includes/report.php文件应该有:

require_once PATH.'/includes/custom-functions.php';
// your other code here ...
$infusion = infusion();

可能是你在文件中包含的其他文件/类已经要求custom-functions.php了,所以你可以完全跳过它。还要注意,在尝试使用PATH常量之前,它应该已经在某个地方定义过了(直接或通过 included文件)。如果你将error_reporting设置为包含E_ALL,如果该常量不存在,你将在错误日志中得到通知。

如果失败,您的错误日志可能会提供一些关于您的问题的额外背景。