【问题标题】:use call_user_func in PHP 8 returns fatal error在 PHP 8 中使用 call_user_func 返回致命错误
【发布时间】:2021-04-14 22:02:11
【问题描述】:

我正在尝试使用函数 handleContactcall_user_func([ContactController::class, 'handleContact']); 调用名为 ContactController 的类,但出现以下错误:

致命错误:未捕获错误:无法静态调用非静态方法 app\controllers\ContactController::handleContact()

<?php
namespace app\controllers;

class ContactController {
    public function handleContact() {
        return 'Hello World';
    }
}

【问题讨论】:

    标签: php php-8


    【解决方案1】:

    如果方法handleContact 是静态的而不是调用它:

    call_user_func([ContactController::class, 'handleContact'])
    

    如果您的方法 handleContact 不是静态的,那么您需要传递一个实例化的类,例如

    $contactController = new ContactController();
    call_user_func([$contactController, 'handleContact'])
    

    附:将 handleContact 设置为静态将是一种简单的方法。

    【讨论】:

    • 感谢您的反馈。可惜我贴错了。我称该功能与您描述的相同。已调整我的问题以反映这一点。
    • 我刚刚更新了我的回复。试试看,希望有帮助。
    • 非常感谢。这个解决方案效果很好
    【解决方案2】:

    由于handleContact 不是静态方法,您应该先实例化您的ContactController,然后在创建的实例上调用该函数。

    您甚至不需要在现代 PHP 中使用丑陋的 call_user_func(),因为您可以直接通过 () 调用回调。

      $controller = new ContactController();
      [$controller, 'handleContact']();
    

    但是,如果您的 handleContact 方法不直接对 ContactController 实例进行操作(即不使用 $this 变量),您可以通过在方法定义中使用 static 关键字将您的方法转换为静态,然后您的原始代码应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-12
      • 2015-11-06
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 2012-08-21
      • 2017-01-13
      相关资源
      最近更新 更多