简体   繁体   中英

Store function result to variable for later use in PHP?

Considering the time I've been using PHP I feel shame for asking this, but it seems I'm way too tired to solve it by myself at this moment.

I have a php variable function that gets an CSV file and stores the data into an array.

$csvdata = function(){
    // Get CSV data to array
    return $array;
}

This array is used by other functions in different situations.

The thing is that I though this functions will run just once, but I just noticed it runs every time I use the var $csvdata.

What I want is to create a self evoked function that runs only once and store the data into an array that I can use as many times as needed without PHP re-doing the process of getting the csv and storing the data every time I use $csvdata.

Its really weird because I feel like if my brain is playing a joke on me... (Brain: "It's obvious... I know the answer but I wont tell you")

Sorry pals

You can call newly created functions on the fly with call_user_func :

$csvdata = call_user_func(function(){
    // Get CSV data to array
    return $array;
});

Then just reference $csvdata as a variable (without parenthesis).

Explanation

The documentation calls the argument to call_user_func a callback, and that is what it is: you pass a function reference to it, and it is the implementation of call_user_func that calls your function for you ("calling you back"). The function reference can be an inline, anonymous function (like above).

But it can also be a variable representing a function:

$func = function(){
    // Get CSV data to array
    return $array;
};
$csvdata = call_user_func($func);

Or, it can be a string, which holds the name of the function:

function myFunc(){
    // Get CSV data to array
    return $array;
};
$csvdata = call_user_func('myFunc');

All of these do the same: your function gets called. You can even tell call_user_func which arguments to pass to your function:

function myFunc($arg){
    echo $arg;
    // Get CSV data to array
    return $array;
};
$csvdata = call_user_func('myFunc', 'hello');

The above will echo 'hello'.

I provide these variants just for information, as your interest is in the inline function argument. Also then you can pass arguments:

$csvdata = call_user_func(function($arg1, $arg2){
    echo $arg1 . "," . $arg2;
    // Get CSV data to array
    return $array;
}, 'hello', 'there');

you can give a name to the function and make a call like this

  function csv(){
        // Get CSV data to array
        return $array;
    }

    $csvdata=csv();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM