PHP doesn't have an explicit statement to initialise variables, like Javascript's var. PHP variables get initialised when they're first assigned to. It's a design choice, for better or worse. To create a variable you always have to assign something to it. Since a variable must have some value and PHP's value for "nothing" is null, you want:

$variable = null;

(Alternative ways to create variables exists, like references, e.g.: parse_str(bar); var_dump($bar);, but let's leave that aside.)

The var statement exists in Javascript to determine scope; Javascript has nested scopes and needs an explicit initialisation to determine what a variable's scope is. Scoping in PHP works differently and doesn't have that ambiguity, hence such a separate statement isn't necessary. Originally PHP also liked implicit globals a lot (a terrible idea in hindsight), which somewhat clashes with the idea of explicit initialisation statements in the first place.

var $var; (a variable declared, but without a value)

That is an incomplete/incorrect quote, it should be "a variable declared but without a value in a class", since that's the only place the var keyword can be used.


As an example, Python also uses initialisation-by-assignment, and also has nested scope. It uses a different approach to resolve this:

foo = 42

def bar():
    foo = 69

    def baz():
        nonlocal foo
        foo = 2

The rule in Python is, that a variable is local to a function if any assignment is done to the variable inside the function. So the foo = 69 creates a new local variable inside bar here. To allow assignment to the variable from an inherited scope, the nonlocal or global keyword must be used to explicitly denote that variable as inherited. foo = 2 here reassigns foo = 69, but neither reassigns foo = 42.

Answer from deceze on Stack Overflow
Top answer
1 of 3
3

PHP doesn't have an explicit statement to initialise variables, like Javascript's var. PHP variables get initialised when they're first assigned to. It's a design choice, for better or worse. To create a variable you always have to assign something to it. Since a variable must have some value and PHP's value for "nothing" is null, you want:

$variable = null;

(Alternative ways to create variables exists, like references, e.g.: parse_str(bar); var_dump($bar);, but let's leave that aside.)

The var statement exists in Javascript to determine scope; Javascript has nested scopes and needs an explicit initialisation to determine what a variable's scope is. Scoping in PHP works differently and doesn't have that ambiguity, hence such a separate statement isn't necessary. Originally PHP also liked implicit globals a lot (a terrible idea in hindsight), which somewhat clashes with the idea of explicit initialisation statements in the first place.

var $var; (a variable declared, but without a value)

That is an incomplete/incorrect quote, it should be "a variable declared but without a value in a class", since that's the only place the var keyword can be used.


As an example, Python also uses initialisation-by-assignment, and also has nested scope. It uses a different approach to resolve this:

foo = 42

def bar():
    foo = 69

    def baz():
        nonlocal foo
        foo = 2

The rule in Python is, that a variable is local to a function if any assignment is done to the variable inside the function. So the foo = 69 creates a new local variable inside bar here. To allow assignment to the variable from an inherited scope, the nonlocal or global keyword must be used to explicitly denote that variable as inherited. foo = 2 here reassigns foo = 69, but neither reassigns foo = 42.

2 of 3
1

There is no var keyword which works the same way as in javascript. From w3schools:

Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.


Your other question:

If it's not possible, is there any logical explanation why it wasn't implemented in PHP?

One logical explanation could be that in PHP all variables start with a $ symbol. So PHP immediately knows when something is a variable and not a function or keyword, without the need for a declaration.

In fact, javascript code also works without declarations, but here, they are still recommended in most cases.


If you want to declare a variable and set its value to null in PHP, just use:

$myVar = null;
🌐
PHP
php.net › manual › en › language.variables.basics.php
PHP: Basics - Manual
Example #4 Default value of an uninitialized variable · <?php // Unset AND unreferenced (no use context) variable. var_dump($unset_var); ?> ... Warning: Undefined variable $unset_var in ...
🌐
Techaltum
tutorial.techaltum.com › variables-in-php.html
variable in php | how to declare variable in php | use of variable in php
In programming, variable is a storage location where data will be stored. In php we declared variable using $(Dollar) symbol. ... Note:-var_data is a variable name. It can be anything or any datatype like string, number, boolean etc. ... You can also declare and assign value in single line.
🌐
W3Schools
w3schools.com › php › php_variables.asp
PHP Variables
Note: When you assign a text value to a variable, put quotes around the value. Note: Unlike other programming languages, PHP has no command for declaring a variable.
🌐
w3resource
w3resource.com › php › variables › declaring-php-variables.php
PHP variables - w3resource
To do this we use the global keyword before the variables. Consider the following the example : ... <?php $x=2; $y=4; $z=5; $xyz=0; function multiple() { global $x, $y, $z, $xyz; $xyz=$x*$y*$z; } multiple(); echo $xyz; ?>
🌐
Tutorial Republic
tutorialrepublic.com › php-tutorial › php-variables.php
How to Define a Variable in PHP - Tutorial Republic
Variable values can change over the course of a script. Here're some important things to know about variables: In PHP, a variable does not need to be declared before adding a value to it.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › php tutorial › variables in php
Variables in PHP | How to declare & Initialize variable in PHP with its Types
March 16, 2023 - Guide to Variables in PHP. Here we discuss what are variables in PHP, how do we declare and initialize variables, and types of variables.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
Find elsewhere
🌐
DopeThemes
dopethemes.com › home › php declaring null variable
PHP Declaring Null Variable - DopeThemes
September 5, 2024 - In PHP, declaring a variable as NULL is a simple way to initialize a variable with no value. Using the settype() function, you can later change the variable’s type as needed. This is especially useful in scenarios where variables need to be ...
🌐
Plus2Net
plus2net.com › php_tutorial › php-variables.php
Variables in PHP the syntax declaration and using
February 5, 2000 - We can retain the value and use them for subsequent function calls by declaring them as Static variable. <?Php function my_function(){ static $my_static_variable=0; $my_local_variable=0; $my_static_variable=$my_static_variable + 1 ; $my_local_variable=$my_local_variable + 1 ; echo "Static variable :".$my_static_variable; echo ",Local Variable :".$my_local_variable; } my_function(); echo "<br>"; my_function(); ?> Output is here.
Top answer
1 of 3
10

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'
2 of 3
2

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.

🌐
Alanastorm
alanastorm.com › phps-safe-ish-types-and-the-return-of-initialization
PHP’s Safe-ish Types and the Return of Initialization
June 21, 2021 - If an end user programmer doesn’t include an initial value for a variable, the program will use a value like null, None, undefined, etc. While this behavior comes with its own set of problems (Call to a member function on a non-object, NullPointerException, etc.), the problems are at least consistent. Worrying about garbage memory isn’t something you’ll do often if you’re working in these languages. The core PHP languages continues to add features from more strongly typed languages.