Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 383
Luis Rivera Avatar asked Jun 02 '26 03:06

Luis Rivera


1 Answers

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');
like image 113
trincot Avatar answered Jun 03 '26 17:06

trincot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!