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.

Moris Renar
  • 1
  • 1
  • 1
  • 3
    You could [return a value](http://php.net/manual/en/functions.returning-values.php) from the function, [pass by reference](http://php.net/manual/en/language.references.pass.php), or set the variable to [global](http://php.net/manual/en/language.variables.scope.php#language.variables.scope.global). – showdev Sep 09 '16 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"; }` – Rajdeep Paul Sep 09 '16 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 09 '16 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? – Bhargav Rao Sep 09 '16 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 09 '16 at 20:50

2 Answers2

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.

aaronofleonard
  • 2,546
  • 17
  • 23
  • 3
    +10 for explaining the crucial *reference* part. You might want to add this reference as well, [http://php.net/manual/en/language.references.php](http://php.net/manual/en/language.references.php). – Rajdeep Paul Sep 09 '16 at 20:32
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

Community
  • 1
  • 1
RPichioli
  • 3,245
  • 2
  • 25
  • 29