Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value of variables in PHP?

Tags:

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?

like image 853
Nate Avatar asked Nov 19 '12 19:11

Nate


People also ask

What is the default value of variable?

Variables of any "Object" type (which includes all the classes you will write) have a default value of null. All member variables of a Newed object should be assigned a value by the objects constructor function.

What is the default function in PHP?

PHP allows you to define C++ style default argument values. In such case, if you don't pass any value to the function, it will use default argument value. Let' see the simple example of using PHP default arguments in function.

How can we set default value to the variable?

You can set the default values for variables by adding ! default flag to the end of the variable value. It will not re-assign the value, if it is already assigned to the variable.

What is $$ variable in PHP?

In PHP, $var is used to store the value of the variable like Integer, String, boolean, character. $var is a variable and $$var stores the value of the variable inside it.


1 Answers

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
like image 164
ThiefMaster Avatar answered Oct 08 '22 14:10

ThiefMaster