PHP Tutorial
PHP Data Types
PHP supports a variety of data types like:
- Integer
- String
- Boolean
- Array
- Float(or Double)
- NULL
- Object
The PHP var_dump
is a function that returns a value and its data type.
Integer
A data type which is a non-decimal number between -2,147,483,648
and 2,147,483,647
.
An integer can be assigned to a variable.
<?php
$integer = 10;
var_dump($integer); //outputs: int(10)
?>
//php-data-types-integer-example-1
String
A string is a collection of characters.
A string can be assigned to a variable.
PHP strings can be single or double quoted.
<?php
echo 'Hi, I am a single-quoted string';
echo "Hi, I am a double-quoted string";
//php-data-types-string-example-1
?>
Boolean
A boolean is a data type that can either be true
or false
A boolean can be assigned to a variable.
<?php
$var = true;
?>
echo
a boolean output the value 1
Array
An array is a data type that stores a collection of values in a single variable.
Arrays assign keys to values.
Arrays can have a collection of other arrays.
Arrays can be used to represent hashmaps.
PHP arrays can be defined by using the array()
function which can also be represented using the short array syntax []
.
<?php
$var = array("Walk", "Run", "Crawl");
var_dump($var);
//OR
$var = ["Walk", "Run", "Crawl"];
var_dump($var);
//php-data-types-array-example-1
?>
[diy=php-data-types-array-example-1][/diy]
Float
A float (also known as a double) is a number that contains a decimal point.
A float can be assigned to a variable.
<?php
$var = 1.2;
var_dump($var); //outputs: float(1.2)
//php-data-types-float-example-1
?>
NULL Value
A variable assigned without a value is by default set to a special data type NULL
.
<?php
$var;
var_dump($var); //outputs: NULL
//php-data-types-null-example-1
?>
Object
A PHP object is a data type is an instance of a class
A class is a scaffold of an object.
Classes are instantiated by the new
keyword.
Let's take for instance a Shape
class which has many properties like:
width
height
color
These properties store values of different data types that are unique on each object instantiation.
The constructor is a function of a PHP class and is automatically called by PHP when the object is instantiated. It is represented by __construct
.
The constructor can accept arguments.
<?php
class Shape {
public $width;
public $height;
public $color;
public function __construct($width, $height, $color) {
$this->width = $width;
$this->height = $height;
$this->color = $color;
}
public function description(){
return 'This shape is '.$this->width.'cm long, '.$this->height.'cm high and is '.$this->color.' in color';
}
}
$shape = new Shape(20,20,'green');
echo $shape->description(); //outputs: This shape is 20 long, 20 high and is green in color
//php-data-types-object-example-1
?>
What You Should Know at the End of This Lesson
- You should know about PHP data types.
- You should be about to output the type of a variable.
- You should know how to define and instantiate an object.