Variable without $, is this possible?

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

For instance:

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

I don’t think so, but the code (not written by me) does not show an error, and I think it is strange. I missed the code, and is also not a constant.

+6
source share
3 answers

In PHP, a constant can be defined which then would not have $ , but the 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 do not change throughout the life of the script.

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

In addition, you cannot interpolate a constant value inside a double-quoted string or HEREDOC:

 $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 can issue a notification for Use of undefined constant a - assumed 'a' and interpret it as an erroneously incorrect string "a" . Look in your error log to see if this is happening. In this case, "a" == TRUE valid because the string "a" nonempty and is compared with the boolean value TRUE.

 echo a == TRUE ? 'true' : 'false'; // Prints true // PHP Notice: Use of undefined constant a - assumed 'a' 
+8
source

With this code:

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

You are not getting any errors because you (or someone else) told PHP not to report errors, warnings or notifications with this code. You set the error report to a higher level and you will receive a notification:

Note: using undefined constant a - assumes 'a' in ...

This means that a is read as a constant with the value "a" . I think this is not what you are actually looking for.

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

The second part of "a" == true will always be true , so it really is:

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

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

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

+2
source

By definition, a variable MUST start with $. In addition, it cannot start with a number, so the variable name, such as $ 1badVar, is invalid. However, it may begin with letters or underscores.

+1
source

Source: https://habr.com/ru/post/895588/


All Articles