View Full Version : easy question
11-13-2012, 10:54 PM
should i use a variable to define a function or just call the function over and over again?
should i do this:
$userstuff = getUserStuff();
insert into ... wherer username = $userstuff
or should i do this
insert into ... wherer username = getUserStuff()
Like which one is more efficient? Defining the function once or just keep doing it for every instance needed?
11-13-2012, 11:32 PM
Your terminology is a little off. You aren't defining a function using a variable. You are assigning the value returned from your function to a variable. As for which is better to use depends upon your situation and coding style preferences. If you only need that returned value once then obviously it might make more sense to simply call the function where you need the value. If you plan to use that value in various places then it might make more sense to declare your variable at the scope level you need and assign it a value with your function call where needed.
11-13-2012, 11:56 PM
The easiest way I can describe it is: if the method itself generates dynamically changing data (for which you are not dealing with via referencing), then call the function when needed. If its static results (whether dynamic in generation or not, I refer to static in the sense of this run only), then assign it to a variable to save the processing required for the function call.
getUserStuff() sounds like it would qualify as "static". So no matter where you call it, it will always have the same data for this script load. Therefore, assigning it to a result makes the most sense.
Spooks mentioned your terminology is off as well. What you describe is more of a closure type in PHP:
$myfunc = function()
Or using a variable function, call_user_func approach, or create_function function (the above requires closure which I believe was 5.3+).
Powered by vBulletin® Version 4.2.2 Copyright © 2015 vBulletin Solutions, Inc. All rights reserved.