user007
user007

Reputation: 3243

PHP - set a variable which does not neet to call using global

I have a variable called

$variable

And when I call it inside a function then I need to use

some_function(){
global $variable;
echo $variable['array'];
}

But I dont want to use a global every time, Is there a way so by which I can call variable without setting a global everytime???

Thanks for your time.

Upvotes: 0

Views: 45

Answers (3)

user557846
user557846

Reputation:

standard practice ...

some_function($variable){
echo $variable['array'];
}

called like any other function:

some_function($variable);

Upvotes: 4

ivansu
ivansu

Reputation: 59

In case you don't want to use "global", you may use $GLOBALS superglobal variable:

function some_function() {
    echo $GLOBALS['variable']['array'];
}

$GLOBALS is an associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

http://www.php.net/manual/en/reserved.variables.globals.php

Upvotes: 1

Hanky Panky
Hanky Panky

Reputation: 46900

You can Pass it as a parameter to your function

$variable=array(2,5,6,9,7);

some_function($param){
  print_r($param);  // this is your variable
}

call it like

some_function($variable);

Upvotes: 1

Related Questions