Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: easy question

  1. #1
    New Coder
    Join Date
    Dec 2011
    Posts
    34
    Thanks
    2
    Thanked 0 Times in 0 Posts

    easy question

    should i use a variable to define a function or just call the function over and over again?

    eg.

    should i do this:
    $userstuff = getUserStuff();
    insert into ... wherer username = $userstuff
    if($userstuff =1)
    {
    echo ok
    }

    or should i do this
    insert into ... wherer username = getUserStuff()
    if(getUserStuff()=1)
    {
    echo ok
    }

    Like which one is more efficient? Defining the function once or just keep doing it for every instance needed?

  • #2
    Supreme Overlord Spookster's Avatar
    Join Date
    May 2002
    Location
    Marion, IA USA
    Posts
    6,280
    Thanks
    4
    Thanked 83 Times in 82 Posts
    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.
    Spookster
    CodingForums Supreme Overlord
    All Hail Spookster

  • #3
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    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:
    PHP Code:
    $myfunc = function()
    {
        print 
    __FUNCTION__;
    };

    print 
    $myfunc(); 
    Or using a variable function, call_user_func approach, or create_function function (the above requires closure which I believe was 5.3+).


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •