Search code examples
phpphp-8

use call_user_func in PHP 8 returns fatal error


I am trying to call a class named ContactController with the function handleContact with call_user_func([ContactController::class, 'handleContact']); but got following error:

Fatal error: Uncaught Error: Non-static method app\controllers\ContactController::handleContact() cannot be called statically

<?php
namespace app\controllers;

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

Solution

  • If the method handleContact is static than call it:

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

    If your method handleContact is not static than you need to pass an instantiated class e.g.

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

    P.S. Setting the handleContact to static would be the easy way out.