简体   繁体   中英

How to assign global variable value in a function in php?

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.

<?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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM