0

i need to assign a global variable value by passing it in a function, something like static variable i guess. Here is my code

<?php

//this is old value
$var = "Old Value";

//need to change the value of global variable
assignNewValue($var);
echo $var;

function assignNewValue($data) {
    $data = "New value";
}
?>

After the execution the value of var need to be New Value. Thanks in advance.

5
  • 3
    You could return a value from the function, pass by reference, or set the variable to global.
    – showdev
    Sep 9, 2016 at 20:23
  • What you're doing is, passing a copy of the variable to the function assignNewValue(). Instead, just do this: function assignNewValue(){ global $var; $var = "New value"; } Sep 9, 2016 at 20:26
  • i need to assign a global variable - no, you don't but you will. And your code will suck. Not now, but soon. By suck, I mean that you will shoot your own foot and lose time wondering what the hell just happened. Good luck.
    – N.B.
    Sep 9, 2016 at 20:44
  • @N.B. Don't you think it's better to inform the user, as to why global vars are considered bad, more constructively? Sep 9, 2016 at 20:46
  • @BhargavRao - no. I think it's clear from what I wrote that it's bad. Plus, the guy's probably not mentally challenged, he can ctrl + t and google "global variable bad".
    – N.B.
    Sep 9, 2016 at 20:50

2 Answers 2

4
<?php

//this is old value
$var = "Old Value";

//need to change the value of global variable
assignNewValue($var);
echo $var;

function assignNewValue(&$data) {
    $data = "New value";
}
?>

I made the argument of assignNewValue a reference to the variable, instead of a copy, with the & syntax.

1
1

You can try it in 2 ways, the first:

// global scope
$var = "Old Value";

function assignNewValue($data) {
   global $var;
   $var = "New value";
}

function someOtherFunction(){
    global $var;
    assignNewValue("bla bla bla");
}

or using $GLOBALS: (oficial PHP's documentation: http://php.net/manual/pt_BR/reserved.variables.globals.php)

function foo(){
  $GLOBALS['your_var'] = 'your_var';
}
function bar(){
  echo $GLOBALS['your_var'];
}
foo();
bar();

Take a look: Declaring a global variable inside a function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.