Hello im interested in understanding how variables are stored in php.
say i have two variables
$p = 1 + 1
$b = $p.
Does php save the result of the variable or does it save the procedure to run it? Why im wondering is if i store a function in it, does it store the return value or just copies the procedure.
Thank you!
Edit: I think it be best if i clarified what im talking about.
say:
function foo($something)
{
for loop
{
echo 'Something';
}
return $something;
}
$b = foo(5);
echo $b;
from what i encountered just assigning the value executes the function. And when i echo $b it also executes the function again.
So what you're wondering if you're assigning like this
$a = function($arg){
echo($arg);
}
$b = $a;
will you have a duplicate of function in memory?
Oops turns out i'm wrong. PHP uses copy-on-write mechanism, which makes both $b
and $a
use the same memory buffer UNLESS any of these variables are modified.
Other possibility is you're wondering what happens when you do something like
$a = 5; $b = 15;
$c = sin($b)*sqrt($a);
Then, only the value of these calculations will be stored in memory, nothing more.
I hope I did understand what question you really wanted to ask!
PHP (like any other language) stores values inside variables. Not more, not less. So the question is: what is a value? :-)
In the example you gave the value (int)2
is stored in both, $p
and $b
.
You can store a function inside a variable and there are even more possibilities. It is more a question of how you code, not of how php stores such thing:
$func = create_function('$a','return sprintf("*-%s-*", $a);');
echo $func('hello'); // will return "*-hello-*"
You can also call a functions existing in a permanent manner via a variable:
function echo_a($a) { return sprintf("*-%s-*", $a); }
$func = 'echo_a';
echo call_user_func($func, 'hello'); // will return "*-hello-*"