-2
$var = "Value 1";

function setVar() {
    global $var;
    $var = "Value 2";
} 

function test($someVar) {
    echo $someVar;
} 

test($var);

I want the output of test(setVar()) to be "Value 2", but without returning $var within setVar(). Is this possible?

Tom Oakley
  • 6,065
  • 11
  • 44
  • 73
  • `setVar` doesn't return anything, so you are passing nothing into the `test` function. If you want to print `$var` in the `test` function, why don't you print it instead of `$someVar`? – Niels B. Jan 25 '14 at 18:48
  • If `setVar` doesn't return anything, then what relationship is there to `test`? – deceze Jan 25 '14 at 18:50
  • Ok so how would I write it so setVar does return $var? Thing is, in my 'proper' code (which is far too complicated to put here) setVar() returns something else and I just need the value of $var available outside of my setVar function so I can pass it as a parameter to test(). Sorry for being so stupid but I've been stuck on this all day :( – Tom Oakley Jan 25 '14 at 18:50
  • You need to restructure whatever you're trying to do. Functions are simple input-output devices and there are patterns to work with that. It's impossible to say what problem you're actually trying to solve and how it is best solved, but what you're trying to do here is not it. – deceze Jan 25 '14 at 18:53
  • Ok I've slightly changed the code so that test() now executes with the parameter $var instead of setVar as I realised that was stupid as it wasn't returning anything (thanks for pointing that out). **How would I get $var to = "Value 2", outside of the setVar function?** Thanks for the help guys and sorry for being stupid? – Tom Oakley Jan 25 '14 at 19:02
  • Never use `global`. You can do what you want through references. – Major Productions Jan 25 '14 at 19:10

1 Answers1

0

Don't use global. Never use global. Use a reference instead:

$var = "Value 1";

function setVar(&$x)
{
    $x = "Value 2";
}

function test($y)
{
    echo $y;
}

setVar($var);

test($var);
Major Productions
  • 5,914
  • 13
  • 70
  • 149