使用其他 类 的函数扩展 CakePHP 的 AppController

Extending CakePHP's AppController with functions from other classes

我不想通过应用程序根目录中 'library' 文件夹中另一个 class 的功能扩展默认的 AppController class。

此刻,我可以通过在我的 class 定义上方添加一个 @property 声明来实现 class 及其功能,如下所示。但是当我 运行 应用程序返回 Call to a member function showTest() on boolean 异常时。这是因为我没有以那种方式声明名称空间或其他东西吗?

// Default class inside 'root/src/Controller/'
/**
* Class    AppController
*
* @property testControl $testControl
*
* @package     App\Controller
*/
class AppController extends Controller
{
    public function initialize() {
        parent::initialize();
    }

    public function beforeFilter(Event $event) : void
    {
       $this->testControl->showTest();
    }
}

// The class inside folder 'root/library/' 
class testControl
{
    public function showTest() {
        die("test");
    }
}

您需要在调用方法之前创建 testControl 对象的新实例:-

public function beforeFilter(Event $event) : void
{
    $testControl = new testControl;
    $testControl->showTest();
}

您看到的 PHP 错误是因为您尚未启动对象并且 $this->testControl 尚未定义。

您还需要通过在文件顶部添加 use 语句或引用来确保告诉 PHP 在哪里可以找到 testControl class启动对象时的命名空间。