Using the Call_user_func function, you can call custom functions by passing in string functions and support references.
1.mixed Call_user_func (Callable $callback [, Mixed $parameter [, mixed $ ...]])
Invokes the custom function provided by the first argument, followed by the parameters of the custom function, and returns the result of the custom function
function Say ($word)
{
Echo $word;
}
Call_user_func (' say ', ' Hello World '); Hello World
You can use Call_user_func to execute a method of a class, and you can pass arguments to a method, and how does it differ from instantiating a class and then calling a method? Look at the example below.
Class A
{
Public function __construct ($a, $b, $c)
{
echo ' construct '. $a. $b $c;
}
Public function test ($a, $b, $c)
{
echo ' Test '. $a. $b. $c;
}
}
$a = new A (1,2,3);
$a->test (1,2,3);
Call_user_func ([' A ', ' Test '],1,2,3);
Class A has a constructor method, if new A is instantiated, the constructor is executed, and the test method is called using Call_user_func, and there is no starting constructor, although all can be executed to the method, which is the difference between the two.
So in some cases, it is not possible to instantiate a class directly, hope to get a class by other means, and how to perform the construction of the class?
You can then use the class's reflection class and Newinstanceargs to create an instance of a new class with the following code:
$reflection = new Reflectionclass (' A ');
$newclass = $reflection->newinstanceargs ([1,2,3]);
$newclass->test (1,2,3);
Its effect is equivalent to:
$a = new A (1,2,3);
$a->test (1,2,3);
You can see the details
First, define a Class A, use Reflectionclass to get a reflection class object, through the Reflectionclass object can get various properties of the class, including namespaces, parent class, class name, etc. Use Newinstanceargs to create an instance of a new class by passing parameters to the constructor.
Class A
{
Public $name;
Public function __construct ($name, $des)
{
$this->name = $name. ', '. $des;
}
Public Function AA ()
{
Echo $this->name;
}
}
$class = new Reflectionclass (' A ');
$AAA = $class->newinstanceargs ([' Www.111cn.net ', ' blog ']);
$aaa->aa ();
Output Result: Www.111cn.net,blog
The $AAA in the above example is a new instance of Class A, created by Newinstanceargs, so it can call method AA () of Class A, and it is noteworthy that Newinstanceargs creates a new class that must be called, which means that the class has to be constructed.