We know we can't store a function in variable
<?php
$k = echo("hello");
?>
or
$k = unset($_SESSION['name']);
They all will give error. because we can't store a function in variable directly, but how we can use.
$row = mysqli_fetch_assoc($result);
I know mysqli_fetch_assoc()
function output an array which is stored in variable $row
. but how a general rule of php is violated. and we are able to store function in a variable
echo
and unset
are not really functions. If you check the documentation, you'll see that it says:
Return Values
No value is returned
Since no value is returned, you can't assign them to variables.
mysqli_fetch_assoc()
is an ordinary function. And like any other function, you can assign its return value to a variable, or pass it as an argument to another function, or use it in an expression.
You would have a hard time programming in PHP if you couldn't assign function values to variables. You couldn't write things like:
$max = max($var1, $var2);
$current_time = time();
We know we can't store a function in a variable
This is not true, but I'll get back to it later.
You are misunderstanding the syntax below:
$variable = functionName();
This does not mean that the function is stored in a variable. It means that the value returned by the function is stored in the variable.
So there is nothing special about:
$row = mysqli_fetch_assoc($result);
You should also know as I hinted at in the beginning, that we can in fact store a function in a variable:
//store the function in variable $func
$func = function($a, $b){return $a + $b;}
//execute the function stored in variable $func
echo $func(2,8); //prints 10
These types of functions -- functions without names -- care called anonymous functions or closures. See the manual