Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable without $, can it be possible?

is it possible that a variable is referenced without using the $?

For example:

if ($a != 0 && a == true) {
...
}

I don't think so, but the code (not written by me) doesn't show an error and I think it's weird. I've overlooked the code and a is not a constant either.

like image 788
deb Avatar asked Aug 22 '11 13:08

deb


2 Answers

In PHP, a constant can be defined, which would then not have a $, but a variable must have one. However, this is NOT a variable, and is not a substitute for a variable. Constants are intended to be defined exactly once and not changed throughout the lifetime of the script.

define('a', 'some value for a');

Additionally, you cannot interpolate the value of a constant inside a double-quoted or HEREDOC string:

$a = "variable a"
define('a', 'constant a');

echo "A string containing $a";
// "A string containing variable a";

// Can't do it with the constant
echo "A string containing a";
// "A string containing a";

Finally, PHP may issue a notice for an Use of undefined constant a - assumed 'a' and interpret it as a mistakenly unquoted string "a". Look in your error log to see if that is happening. In that case, "a" == TRUE is valid, since the string "a" is non-empty and it is compared loosely to the boolean TRUE.

echo a == TRUE ? 'true' : 'false';
// Prints true
// PHP Notice:  Use of undefined constant a - assumed 'a'
like image 67
Michael Berkowski Avatar answered Oct 14 '22 07:10

Michael Berkowski


With this code:

if ($a != 0 && a == true) {
    ...
}

You're not getting any error because you (or someone else) have told PHP to not report any errors, warnings or notices with that code. You set error reporting to a higher level and you will get a notice:

Notice: Use of undefined constant a - assumed 'a' in ...

Which will mean that a is read as a constant with a value of "a". This is not what you're actually looking for I guess:

if ($a != 0 && "a" == true) {
    ...
}

The second part "a" == true will always be true, so this is actually like so:

if ($a != 0) {
    ...
}

As it's not your code, one can only assume that this was not intended by the original author.

So: Variables in PHP always start with the dollar sign $. Everything else is not a variable.

like image 36
hakre Avatar answered Oct 14 '22 08:10

hakre