This may sound like a dumb question, but does assigning a variable to a function mean it only calls the function ONE time, and can be reused unlimited times without making an additional call to the function or does it still call the function multiple times?
is this:
$variable = function_name();
echo $variable;
echo $variable;
the same as this:
echo function_name();
echo function_name();
I understand both situations are ultimately displaying the same bit of information, but I’m curious if that bit of data is fetched one time and reused many, or if it’s fetched upon each echo.
So does assigning a variable to a function mean function_name(); does the work only ONE time and the variable just recycles the data for later usage or does function_name(); actually do the work TWO times?
Is it better practice to assign variables or just directly call the function each time it needs to be used?
a function should always return some values so for example, if you have a function like this.
and if you call it and assign it to a variable then
if you try printing the variable
$ait will simply print the value it contains and not call the function once again, since$anow contains ‘hello world’;by echoing $a variable multiple times.
will simply print the value
hello worldthree times and not call the function three times.but when you call the function multiple times for example.
now coming to your question.
i hope i have explained this in full details.
well it depends on the context, and the function you want to use, the bottom line is, always try returning some values from the function, for example.
a) if the function is meant for fetching some values and formatting it, then should return it as array, string or whatever data type.
b) if the function is meant to do some execution and not any fetching, then you can return boolean values like
return true|falseindicating wether the operation was successful.