Skip to content
Advertisement

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 appcontrollersContactController::handleContact() cannot be called statically

<?php
namespace appcontrollers;

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement