php - Calling a function with call_user_func
Get the solution ↓↓↓I am struggling with calling a function with call_user_func!
I want to call the function by$application->performAction('user', 'create')
;
Application.php:
<?php
class Application
{
public $controllers = [];
public function __construct($controllers)
{
array_push($this->controllers, $controllers);
}
public function performAction($model, $action)
{
call_user_func($this->controllers[$model], $action);
}
}
UserController.php:
<?php
require './models/User.php';
class UserController
{
public function create()
{
}
...
}
index.php:
<?php
require_once './core/Application.php';
require_once './controllers/UserController.php';
...
$controllers = [
'user' => new UserController(),
...
];
$application = new Application($controllers);
$application->performAction('user', 'create');
Answer
Solution:
You're making 2 serious mistakes in your code.
With array_push you add an array to an array and get a 2-dimensional array. This is not necessary. The following is sufficient:
$this->controllers = $controllers;
call_user_func expects a callable function as the first parameter. For classes, an array must be taken as the first parameter.
You don't even need call_user_func to call a method. I added an alternative as a comment. I think this can also be understood better. Have expanded your code to better show it all.
<?php
class UserController
{
public function create($par)
{
var_dump('create from '.__CLASS__.' with('.$par.')');
}
}
class Application
{
public $controllers = [];
public function __construct(array $controllers)
{
$this->controllers = $controllers;
}
public function performAction($model, $action)
{
call_user_func([$this->controllers[$model],$action],"par_1");
//$this->controllers[$model]->$action("par_1");
}
}
$controllers = [
'user' => new UserController(),
];
$application = new Application($controllers);
$application->performAction('user', 'create');
//output: string(38) "create from UserController with(par_1)"
Try the second variant yourself. Call_user_func() is blocked in the PHP sandbox.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: git was not found in your path, skipping source download
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.