PHP is a weak typing language. This means that it is not necessary to set a type for the variable.
So it's like you said:
it creates the type of the variable at boot time
Example:
$int = 1;
$float = 1.44;
$string = 'stackoverflow';
$boolean = false;
$array = array();
$object = new stdClass;
You can test the types of these variables through functions like is_string
, is_float
, is_int
and is_boolean
.
You can also get the name of the variable type through the function gettype
.
Example:
$array = array(1, 2, 3);
gettype($array); // array
Induction of Types
In PHP it is possible to "induce specific (not all) types" for parameters passed in functions.
We can check if a given object is a given instance or sub-instance. If it implements an interface, whether it is a callback, or if it is an array.
Type induction examples for classes:
class X{
public function get(){}
}
function usa_x(X $x){
return $x->get();
}
usa_x(new X);
Array type induction examples:
function usa_array(array $array){
foreach($array as $key => $value);
}
usa_array(1); // gera um erro!
Type induction examples for callbacks (as of php 5.4):
function usa_callback(callable $callback)
{
return $callback(1, 2, 3);
}
usa_callback('var_dump');
usa_callback(function ($a, $b, $c){
var_dump($a, $b, $c);
});
usa_callback('nao_existe'); // gera um erro
SplType
There is an extension called Spl Type
, where you can simulate type definition through instances of specific classes for each type.
Example:
$int = new SplInt(94);
try {
$int = 'Try to cast a string value for fun';
} catch (UnexpectedValueException $uve) {
echo $uve->getMessage() . PHP_EOL;
}
echo $int . PHP_EOL; // Value is not integer
If this is necessary (I think in most cases it is not), here is the link to SplType