I was trying to pass a variable that contained the name of the superglobal array I wanted a function to process, but I couldn't get it to work, it would just claim the variable in question didn't exist and return null.
I've simplified my test case down to the following code:
function accessSession ($sessName)
{
var_dump ($$sessName);
}
$sessName = '_SERVER';
var_dump ($$sessName);
accessSession ($sessName);
The var_dump outside of the function returns the contents of $_SERVER, as expected. However, the var_dump in the function triggers the error mentioned above.
Adding global $_SERVER to the function didn't make the error go away, but assigning $_SERVER to another variable and making that variable global did work (see below)
function accessSession ($sessName)
{
global $test;
var_dump ($$sessName);
}
$test = $_SERVER;
$sessName = 'test';
var_dump ($$sessName);
accessSession ($sessName);
Is this a PHP bug, or am I just doing something wrong?
PHP: Variable variables - Manual
Warning
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.
Solutions
function access_global_v1 ($var) {
global $$var;
var_dump ($$var);
}
function access_global_v2 ($var) {
var_dump ($GLOBALS[$var]);
}
$test = 123;
access_global_v1 ('_SERVER');
access_global_v2 ('test');
From php.net:
Warning
Please note that variable variables cannot be used with PHP's
Superglobal arrays within functions or class methods. The variable
$this is also a special variable that cannot be referenced
dynamically.
The answer is fairly simple: never use variable variables.
Use arrays instead.
(and yes - you are doing something wrong. No, it is not a bug in PHP.)
Use $GLOBALS. There you go :)
<?php
function accessSession ($sessName)
{
var_dump ($GLOBALS[$sessName]);
}
$sessName = '_SERVER';
accessSession ($sessName);
Related
i have following code.
$hello = "World";
$test = "hello";
echo $$test;
When I execute this I get as result: World
So far as good
But when I use a reserved variable, for example $_GET it doesn't work.
$test = "_GET";
var_dump($$test);
Here the result is NULL. Is there a way to get values of a reserved variable throught a variable variable?
Superglobals can only be dereferenced by variable variables in the global scope. The fact you can't get it to work seems to indicate that your code is in a function/method. In this case, you can use the $GLOBALS superglobal:
function foo() {
$str = '_GET';
var_dump($GLOBALS[$str]);
}
foo();
This is PHP 5.4 code...
<?php
function abc($YesNo){return $YesNo["value"];}
$YesNo = array("value"=>"No","text"=>"No");
$x = array("active"=>function(){return abc($YesNo);});
echo $x['active']();
?>
Notice: Undefined variable: YesNo on line 7
Output Should be : Yes
if i directly put array in code by replace $YesNo like
<?php
function abc($YesNo){return $YesNo["value"];}
$x = array("active"=>function(){return abc(array("value"=>"Yes","text"=>"Yes"));});
echo $x['active']();
?>
output : Yes
which is correct output. Now what's the problem in first code. I need that for re-usability
Try this,
You can use use for passing data to a closure.
<?php
function abc($YesNo){return $YesNo["value"];}
$YesNo = array("value"=>"No","text"=>"No");
$x = array("active"=>function() use ($YesNo) {return abc($YesNo);});
echo $x['active']();
?>
You provide your anonymous function with a parameter:
$x = array("active"=>function($param){return abc($param);});
then you call it:
echo $x['active']($YesNo);
You may use the use keyword to make your function aware of an external variable:
$x = array("active"=>function() use ($YesNo) {return abc($YesNo);});
but it would be quite against the idea of reusability, in this case.
The problem is that your variable is not accessible within the function due to Variable Scope.
Because the array is defined outside of the function, it is not by default available inside the function.
There's a couple of solutions
Disclaimer: These are intended to fit within the scope of the question. I understand that they are not necessarily best practice, which would require a larger discussion
First Option:
You can declare the array within the function, like below. This is useful if you don't need access to it outside of the function.
function abc($YesNo){
$YesNo = array("value"=>"No","text"=>"No");
return $YesNo["value"];
}
Second Option:
Within your abc function, you can add the line global $YesNo. This is useful if you do need access to the array outside of the function:
function abc($YesNo){
global $YesNo;
return $YesNo["value"];
}
Other options exist (such as moonwave99's answer).
Finally:
Why are you putting an anonymous function within the array of $x? Seems like a path that will lead to problems down the road....
Your variable $YesNo needs to be visible in the scope of your anonymous function. You need to add global $YesNo as the first statement in that function:
So
$x = array("active"=>function(){return abc($YesNo);});
becomes
$x = array("active"=>function(){global $YesNo; return abc($YesNo);});
... also "value"=>"No" should be "value"=>"Yes" if you want it to return "Yes"
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.
standard practice ...
some_function($variable){
echo $variable['array'];
}
called like any other function:
some_function($variable);
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);
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
I hava a function that looks something like this:
require("config.php");
function displayGta()
{
(... lots of code...)
$car = $car_park[3];
}
and a config.php that look something like this:
<?php
$car_park = array ("Mercedes 540 K.", "Chevrolet Coupe.", "Chrysler Imperial.", "Ford Model T.", "Hudson Super.", "Packard Sedan.", "Pontiac Landau.", "Duryea.");
(...)
?>
Why do I get Notice: Undefined variable: car_park ?
Try adding
global $car_park;
in your function. When you include the definition of $car_park, it is creating a global variable, and to access that from within a function, you must declare it as global, or access it through the $GLOBALS superglobal.
See the manual page on variable scope for more information.
Even though Paul describes what's going on I'll try to explain again.
When you create a variable it belongs to a particular scope. A scope is an area where a variable can be used.
For instance if I was to do this
$some_var = 1;
function some_fun()
{
echo $some_var;
}
the variable is not allowed within the function because it was not created inside the function. For it to work inside a function you must use the global keyword so the below example would work
$some_var = 1;
function some_fun()
{
global $some_var; //Call the variable into the function scope!
echo $some_var;
}
This is vice versa so you can't do the following
function init()
{
$some_var = true;
}
init();
if($some_var) // this is not defined.
{
}
There are a few ways around this but the simplest one of all is using $GLOBALS array which is allowed anywhere within the script as they're special variables.
So
$GLOBALS['config'] = array(
'Some Car' => 22
);
function do_something()
{
echo $GLOBALS['config']['some Car']; //works
}
Also make sure your server has Register globals turned off in your INI for security.
http://www.php.net/manual/en/security.globals.php
You could try to proxy it into your function, like:
function foo($bar){
(code)
$car = $bar[3];
(code)
}
Then when you call it:
echo foo($bar);
I had the same issue and have been tearing my hair out over it - nothing worked, absolutely nothing - until in desperation I just copied the contents of config.php into a new file and saved it as config2.php (without changing anything in its contents at all), changed the require_once('config.php'); to require_once('config2.php'); and it just started working.
I'm having trouble with the following code. What it should do is echo cats.php followed by example.php but it's not echoing the example.php. Any ideas why this might be happening?
$bookLocations = array(
'example.php',
'cats.php',
'dogs.php',
'fires.php',
'monkeys.php',
'birds.php',
);
echo $bookLocations[1];
function findfile($filenumber)
{
echo $bookLocations["$filenumber"];
}
findfile(0);
Try changing,
echo $bookLocations["$filenumber"];
to:
echo $bookLocations[$filenumber];
Edit* To expand on Thomas's correct answer, instead of using global variables, you could change your method to:
function findfile($filenumber, $bookLocations)
{
echo $bookLocations[$filenumber];
}
i believe you may also need to declare the global variable in your function.
global $bookLocations;
Ok, there are two issues.
Variable Scope
Your function doesn't know the array $bookLocations, you need to pass it to your function like so:
function findfile($filenumber, $bookLocations)
Array key
You don't want to wrap your array key in quotes:
wrong: $bookLocations["$filenumber"];
right: $bookLocations[$filenumber];
The quotes in "$filenumber" turn your key into a string, when the keys to your array are all numbers. You are trying to access $bookLocations["1"] when in fact you want to access $bookLocations[1] -- that is to say, 1 is not the same as "1". Therefore, like others have said, you need to get rid of the quotation marks around the key (and check your variable scope too).
function findfile($filenumber)
{
global $bookLocations;
echo $bookLocations[$filenumber];
}
Good-style developers usually avoid global variables. Instead, pass the array to the function as the parameter:
function findfile($files, $filenum)
{
echo $files[$filenum];
}
$bookLocations is out of scope for your function. If you echo $filenumber you will see that it's in scope because you passed it in by value. However, there is no reference to $bookoLocations.
You should pass in $bookLocations
declaration: function findfile($filenumber, $bookLocations){
call: findfile(1, $bookLocations);
You could also to declare $bookLocations as global, but globals should be avoided if possible.