Home  >  Article  >  Backend Development  >  Definition and simple examples of variable functions and callback functions in PHP

Definition and simple examples of variable functions and callback functions in PHP

怪我咯
怪我咯Original
2017-06-19 13:20:411710browse

VariableFunction:1. When assigning the name of a function (String) to a variable, in this Variable name Adding parentheses after it will call the function corresponding to the variable value;

Callback function : 1. When using a function, if you pass When entering a variable cannot solve a big problem, you need to pass a process into the function, thereby changing the execution behavior of the function ;
2. When the function is called, the parameters passed in are It is not a variable or a value, but a function. This is the callback function; (The parameter of the function is a function)

<?php
//变量函数:1.当把一个函数的名称(字符串)赋值给一个变量时,在这个变量名后面加上括号就会调用这个变量值所对应的函数;
function square($a,$b)
{
return $a*$a+$b*$b;
}
$var="square";
echo $var(3,5);//输出34;
echo "<br>";
//回调函数:1.在使用一个函数时如果传入一个变量不能解决多大的问题时就需要传入一个过程进入到函数中,从而改变函数的执行行为;
//          2.在函数的调用时,在参数中传入的不是一个变量或一个值,而是一个函数,这就是回调函数;(函数的参数就是一个函数)
$arr=array("aaaa","aa","aaaadfdfafadfas","a","aaa","adfasfa","afasdfsaffa");
print_r($arr);
echo "<br>";
//创建一个比较函数
function compare($a,$b)
{
if(strlen($a)>strlen($b))
{
return 1;
}
elseif(strlen($a)==strlen($b))
{
return 0;
}
else
{
return -1;
}
}
usort($arr,"compare");//传入函数名compare,调入compare函数所对应的执行过程将数组$arr按照字符串长度升序排列;
print_r($arr);
?>

The above is the detailed content of Definition and simple examples of variable functions and callback functions in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn