Moris Renar
Moris Renar

Reputation: 1

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.

Upvotes: 0

Views: 6971

Answers (2)

RPichioli
RPichioli

Reputation: 3345

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

Upvotes: 1

aaronofleonard
aaronofleonard

Reputation: 2576

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

Upvotes: 4

Related Questions