MENU
Functions
A function is a piece of code which may be called using its name. It can take in arguments and return a value. Unlike variable names, function names are case-insensitive. Structuring a code with functions makes it readable and maintainable.This function takes an array as an argument and returns an array.
Default values, when passed to arguments after =, must appear at the end of the arguments list.
<!DOCTYPE html>
<html>
<head></head>
<body><?php
function sum_product($arr){
$s=0; $p=1;
foreach ($arr as $v){
$s+=$v;
$p*=$v;
}
return [$s,$p];
}
$a=[10,20,30,40];
list($sum,$product)=sum_product($a);
echo $sum.",".$product;
?></body>
</html>
RESETRUNFULL
<!DOCTYPE html>
<html>
<head></head>
<body><?php
function shout($s,$s1="I say: ",$s2="!"){
echo $s1.$s.$s2."<br />";
}
shout ("Hello World");
shout ("Hello World","He says: ");
shout ("Hello World","She says: ",".");
?></body>
</html>
RESETRUNFULL
<!DOCTYPE html>
<html>
<head></head>
<body><?php
function shout(){
echo "Hello World";
}
$f = "shout";
$f();
?></body>
</html>
RESETRUNFULL
<!DOCTYPE html>
<html>
<head></head>
<body><?php
shout();
shout_again(); // error without first calling shout();
function shout(){
echo "Hello World <br />";
function shout_again(){
echo "Hello World";
}
}
?></body>
</html>
RESETRUNFULL
<!DOCTYPE html>
<html>
<head></head>
<body><?php
$a=2; $b=3;
function add(){
global $a, $b;//binds
$a=&$GLOBALS["a"];
$b=&$GLOBALS["b"];
$a+=$b;
unset($a); // no effect on global $a, local $a unbound only
$c=10;
}
add();
echo $a."<br />";
echo isset($c); // false, NULL
?></body>
</html>
RESETRUNFULL
<!DOCTYPE html>
<html>
<head></head>
<body><?php
function f(){
static $a=0;
echo $a;
$a++;
}
f();f();f();
?></body>
</html>
RESETRUNFULL
<!DOCTYPE html>
<html>
<head></head>
<body><?php
function change_noref($n1,$n2){$n1++; $n2++;}
function change_ref(&$n1,&$n2){$n1++; $n2++;}
$a=5; $b=5;
change_noref($a,$b);echo ($a+$b)."<br />";
change_ref($a,$b);echo ($a+$b);
?></body>
</html>
RESETRUNFULL
<!DOCTYPE html>
<html>
<head></head>
<body><?php
$a=5;
function &ref(){
global $a;
return $a;
}
$b =& ref();
$a=10;
echo $b;
?></body>
</html>
RESETRUNFULL
<!DOCTYPE html>
<html>
<head></head>
<body><?php
$f = function(){echo "Hello World";};
function f2($func){
$g=$func;
$g();
}
f2($f);
?></body>
</html>
RESETRUNFULL
<html>
<head></head>
<body><?php
function f($s){
$s2="I say";
$f2= function () use ($s, $s2){
echo $s2." ".$s;
};
$f2();
}
f("Hello World.");
?></body>
</html>
<!DOCTYPE html>
<html>
<head></head>
<body><?php
function f($v1,$v2){
for ($i=0; $i<func_num_args(); $i++){
echo func_get_arg($i);
}
echo "<br />";
echo func_get_args()[0].func_get_args()[1].func_get_args()[2];
}
f(1,2,3,4,5,6,7);
?></body>
</html>
<!DOCTYPE html>
<html>
<head></head>
<body><?php
function f(array $v1, callable $fa, MyClass $ca){
echo $fa().$ca->v2.$v1[1];
}
$g = function(){echo "Hello World";};
class MyClass{public $v2=100;}
$c = new MyClass;
f([100,200],$g,$c);
?></body>
</html>