Variable without $, can it be possible?

2019-04-27 16:05发布

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.

3条回答
放荡不羁爱自由
2楼-- · 2019-04-27 16:14

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'
查看更多
forever°为你锁心
3楼-- · 2019-04-27 16:31

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.

查看更多
姐就是有狂的资本
4楼-- · 2019-04-27 16:36

By definition a variable MUST start with a $. Also, it cannot start with a number so a variable name like $1badVar is invalid. It may however, start with letters or underscores.

查看更多
登录 后发表回答