Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP global keyword and assignment

I have defined a $foo global variable.

Later, I want to set $foo to something else.

public function bar()
{
    global $foo;
    $foo = 'hello';
}

Are there any unexpected side effects to shortening this to one line?

public function bar()
{
    global $foo = 'hello';
}

I have looked in the documentation and don't see them declaring and assigning the variable on the same line. Therefore, I'm wondering if anyone else has experienced issues doing this, or if it's just bad coding practice to put it on one line?

like image 845
Katrina Avatar asked Sep 01 '25 17:09

Katrina


2 Answers

If you attempt to run the code you suggested in your question, you will get a syntax error. You cannot define a global variable like you have above.

If you wanted to still define that value in a single line you could use the $GLOBALS array instead like this:

public function bar(){
    $GLOBALS['foo'] = 'hello';
}

Here's the documentation if you want to have a look.


You could set the variable up here:

function bar(){

    global $hello;
    $hello = "hello";

}

Then later on edit it like this:

function foo(){
    $GLOBALS['hello'] = "world"; 
}

If you ran this code:

bar();
foo();

print_r($GLOBALS);

The value of $GLOBALS['hello'] will be 'world'. When run the other way around with foo(); executing before bar(); you'll get 'hello' as the global value instead.

like image 135
Henders Avatar answered Sep 04 '25 09:09

Henders


My solution in one line without using $GLOBALS:

global $foo; $foo = 'hello';

A bit messy, but still looks better in some cases, than 2 lines of code for one assignment.

like image 43
sbnc.eu Avatar answered Sep 04 '25 08:09

sbnc.eu