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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With