OM The Eternity
OM The Eternity

Reputation: 16244

PHP - What is the default data type of any PHP variable?

PHP is loosely Typed Language but could someone tell me, What is the default data type of any PHP variable? What is its implicit data Type?

Upvotes: 1

Views: 4402

Answers (4)

CD001
CD001

Reputation: 8482

The OP understands that PHP is a loosely typed language and therefore the type of any initialized variable is determined by the data it holds; so read that way, the question then becomes What is the type of an uninitialized variable? - the answer to which is null

PHP doesn't generally allow you to declare variables without initializing them, there's no direct equivalent to:

Dim SomeVar

Therefore the only way to see that "default" data type is to evaluate either a variable that hasn't been set or a class member that holds no data.

1: A variable that hasn't been set

echo $someVar === null ? "NULL" : "NOT NULL"; //outputs NULL (and triggers a Warning)

2: A declared class member that holds no data

class Test {
  public static $someVar;
}

var_dump(Test::$someVar); // outputs NULL

Therefore:

  • the type of any initialized variable is determined by the data it holds

  • the type of any uninitialized variable is null

Upvotes: 3

Igor Levicki
Igor Levicki

Reputation: 1613

Type Juggling

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.

Source: http://www.php.net/manual/en/language.types.type-juggling.php

Upvotes: -1

Grant Thomas
Grant Thomas

Reputation: 45068

From the manual on variables:

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.

So, they are what you make of them.

Upvotes: 6

SamHuckaby
SamHuckaby

Reputation: 1162

PHP's variables are dynamic, and change depending on the data inside them. So they have no datatype by default.

Upvotes: 8

Related Questions