Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - How to pass a global variable to a function

I have a function that populates an array that was created before the function is launched. To make the population work, I used 'global' in my function. Everything is working fine with the here below situation:

$parameter = 'something';  
$listOne = array();

my_function($parameter);

function my_function($para) {
     global $listeOne;
     ...some code  
     $listeOne[0] = 'john';
     $listeOne[1] = 'lugano';
}

What I would like is to pass the array that is supposed to be used in the function when calling the function. The idea would be to do something like this:

$parameter = 'something';  
$listOne = array();
$listTwo = array();

my_function($listOne, $parameter);
...some code
my_function($listTwo, $parameter);

function my_function($list, $para) {
     ...some code
     $list[0] = 'john';
     $list[1] = 'lugano';
}

In addition according to what I read, using global is maybe not the best thing to do... I saw some people using the & sign somewhere and saying it is better. But I don't get it and not find information about that 'method'... Hope I am clear. Thank you in advance for your replies. Cheers. Marc

like image 774
Marc Avatar asked Apr 18 '12 10:04

Marc


2 Answers

It's called referencing:

$listOne = array();

function my_function(&$list, $para) {
     ...some code
     $list[0] = 'john';
     $list[1] = 'lugano';
}
my_function($listOne, $parameter);

print_r($listOne); // array (0 => 'john', 1 => 'lugano');

Now the omitted array will be changed.

like image 188
dan-lee Avatar answered Oct 05 '22 23:10

dan-lee


Maybe you need some thing like "parameters by reference" http://www.php.net/manual/en/functions.arguments.php

like image 41
iMysak Avatar answered Oct 06 '22 01:10

iMysak