Reputation: 59
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';
}
}
Upvotes: 2
Views: 2898
Reputation: 1416
As handleContact
is not a static method, you should instantiate your ContactController
first and then call the function on the created instance.
You don't even need to use the ugly call_user_func()
in modern PHP, as you can invoke the callback directly by ()
.
$controller = new ContactController();
[$controller, 'handleContact']();
If however your handleContact
method doesn't directly operate on ContactController
instance (i.e. doesn't use $this
variable), you can convert your method to static by using the static
keyword in method definition and your original code should work.
Upvotes: 3
Reputation:
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.
Upvotes: 6