Nate
Nate

Reputation: 28384

Default value of variables in PHP?

I did a search for this, but I could not find an answer to my question.

When a variable is declared without a value, like this:

$var;
public $aVar;

Is the value of the variable unknown, as in many languages (i.e. whatever was in memory before), or is the variable by default set to null?

Upvotes: 8

Views: 9823

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318518

Variables that are declared without a value and undefined/undeclared variables are null by default.

However, just doing $var; will not declare a variable so you can only declare a variable without a value in an object.

Demo:

<?php
class Test { public $var; }
$var;
$t = new Test();
var_dump($var);
var_dump($t->var);

Output:

Notice: Undefined variable: var in - on line 5
NULL
NULL

Upvotes: 13

Related Questions