Since PHP is an interpreted language, it is very convenient to compile and call functions. Summarize magic functions, nested functions, anonymous functions, function call methods, and function parameter usage.
Since PHP is an interpreted language, it is very convenient to compile and call functions. Summarize magic functions, nested functions, anonymous functions, function call methods, and function parameter usage.
The following is a simple example.
Function _ autoload ($ class_name)
{
Require_once $ class_name. '. class. php ';
}
In addition, several constants and functions are provided:
$ Func = create_function ('$ a, $ B ','
If ($ a = $ B)
{
Return 0;
}
Return ($ a <$ B )? -1: 1;
');
$ Func = function ($ a, $ B)
{
If ($ a = $ B)
{
Return 0;
}
Return ($ a <$ B )? -1: 1;
}
Function foo ($ arg1)
{
$ Var = 3;
$ Inner = function ($ innerArg) use ($ arg1, $ var)
{
Return $ innerArg + $ arg1/$ var;
};
Echo $ inner (5 );
}
Nested functions can be defined in the parent function body, such:
Function outer ()
{
$ Out_var = 1;
Function inner ()
{
Echo "call inner \ n ";
}
// Echo "call outer \ n ";
}
Outer ();
$ Debug = false;
If ($ debug = true)
{
Function foo ()
{
Echo "foo ";
}
}
Foo ();
The function name can be a variable name.
Function foo ()
{
Echo "call foo ";
}
$ Func = 'foo ';
$ Func ();
When you call a class method, an array is input as the parameter. The first element of the array is the instance or class name, and the second element is the method name:
Class myclass
{
Public $ age = 21;
Function echo_age ()
{
Echo $ this-> age;
}
Static function s_echo_age ()
{
Echo 22;
}
Function I _echo_age ()
{
Echo 23;
}
}
$ C = new myclass;
$ Classname = "myclass ";
Call_user_func (array ($ c, 'echo _ age '));
Echo "\ n ";
Call_user_func (array ($ classname, 'I _ echo_age '));
Echo "\ n ";
Call_user_func (array ($ classname,'s _ echo_age '));
Echo "\ n ";
Call_user_func (array ($ c,'s _ echo_age '));
In this way, you can implement flexible overloading, but it is easy to make the logic responsible and use it appropriately.
Function call_it ($ func)
{
$ Args = func_get_args ();
Call_user_func_array ($ func, $ args );
}
Function add ($ a, $ B)
{
Echo $ a + $ B;
}
Function sqr ($)
{
Echo $ a * $;
}
Call_it ('add', 1, 2 );
Echo "\ n ";
Call_it ('sqr', 2 );