Variables can store data of different types such as:
A string is a sequence of characters. It can be any text inside quotes (single or double):
$x = "Hello!";
$y = 'Hello!';
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
$x = 5;
A float, or floating point number, is a number with a decimal point.
$x = 5.01;
A Boolean represents two possible states: TRUE or FALSE. Booleans are often used in conditional testing.
$x = true;
$y = false;
An array stores multiple values in one single variable.
$colors = array("Magenta", "Yellow", "Cyan");
Null is a special data type that can only have the value null
. Variables can be declared with no value or emptied by setting the value to null
. Also, if a variable is created without being assigned a value, it is automatically assigned null
.
<?php
// Assign the value "Hello!" to greeting
$greeting = "Hello!";
// Empty the value greeting by setting it to null
$greeting = null;
?>
A class is a data structure useful for modeling things in the real world, and can contain properties and methods. Objects are instances a class, and are a convenient way to package values and functions specific to a class.
<?php
class Car {
function Car() {
$this->model = "Tesla";
}
}
// create an object
$Lightning = new Car();
// show object properties
echo $Lightning->model;
?>
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. You can use get_resource_type() function to see resource type.
<?php
// prints: mysql link
$c = mysql_connect();
echo get_resource_type($c) . "\n";
// prints: stream
$fp = fopen("foo", "w");
echo get_resource_type($fp) . "\n";
// prints: domxml document
$doc = new_xmldoc("1.0");
echo get_resource_type($doc->doc) . "\n";