如何在 Joomla 的 public 函数中包含 php 文件?

how to include a php file inside a public function in Joomla?

我想在 class 的帮助下 include/require_once 模板中的 PHP 文件。它不包括应有的文件。仅显示文件的顶部 html 部分。

代替JPATH_BASE,我也尝试了其他选项。

class xyz {

public function loadfile($block) {
    require_once JPATH_BASE.'/templates/'.$block.'.php';
 }
}

$app = new xyz();

$app->loadfile(top);

非常感谢您的帮助。

当您在函数中包含文件时,请记住它将在其上下文中执行,这很可能会破坏某些代码的某些内容。 (例如,如果不调用 global 语句,所有全局变量都将是未定义的)

例如,考虑将此添加到您的 class xyz:

private function test() {
    echo 'test';
}

现在,您可以在包含的文件中输入:

<?php
$this->test();

现在,如果您使用此 class 加载此文件,将输出 test

问题是为什么要借助 class 和函数加载文件,如果真的有必要的话。

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

(https://php.net/manual/en/function.include.php)

(另外,大约只显示页面的顶部,检查包含的文件,它真正包含的内容;同时检查服务器日志中的错误,它们会让您更容易发现问题)