1

As per example below, I would expect the ouput to be "test value", why do I get "0" instead?

File main.php

<?php
include_once 'functions.php';
$var = '0'; 
test();
echo $var; 
?>

File functions.php

<?php 
function test()
{
    global $var;
    $var = 'test value';
}
?>
1
  • 1
    It's not a bug. It's a chance. If the global would be working, you'd couple your function to the global scope. And you'd think this is how it should be done. When in fact, it shouldn't. Globals are EVIL. You are blessed that it doesn't work. Now you have to pass in the value as an argument to the function. And that will give you much cleaner and much more maintainable code in the long run! Don't worry be happy!! Commented Feb 14, 2011 at 21:35

4 Answers 4

2

Your best bet is to do:

   include_once 'functions.php';
   $_GLOBALS["var"] = '0'; 
   test();
   echo $_GLOBALS["var"]; 

and in the function using $_GLOBALS["var"] without making $_GLOBALS a global, it aleady is.

Your code works perfectly: http://codepad.org/zI9xg1sK

Sign up to request clarification or add additional context in comments.

4 Comments

using $_GLOBALS produces the same results as the original code.
Your code works perfectly: codepad.org/zI9xg1sK What PHP Version are you using ?
I am using PHP 5, but it doesn't work, maybe because main.php includes functions.php and main.php is included from another file?
@Gordon, I was totally wrong with that comment, it's been a while since I done some large scale PHP Work, also read my first comment.
1

The only reason I can think of is that main.php is also being included from within a function, making $var a local variable in that function's scope.

In that case, this would help:

<?php
 global $var;
 include_once 'functions.php';
 $var = '0'; 
 test();
 echo $var; 
 ?>

1 Comment

main.php is included from start.php, but not within a function.
1

Why don't you make it with

return $var;

and call function that way:

$var = test();

Comments

0

This is an alternative example. Ian commented on CappY's answer that the real function already returns a value. I assume that is why he thinks he needs a global valriable.

You don't need to (ab)use global variable to return multiple values from a function. Two alternative (and better) options are returning an array, or passing variables by reference.

Example on returning arrays:

function test() {
    return array('value 1', 'value 2');
}

// Example usage
list($var1, $var2) = test();
var_dump($var1); // outputs "value 1"
var_dump($var2); // outputs "value 2"

example passing by reference

function test(&$var2) {
    $var2 = 'value 2';
    return 'value 1';
}

// Example usage
$var1 = test($var2);
var_dump($var1); // outputs "value 1"
var_dump($var2); // outputs "value 2"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.