PHP is a weak typing language. This means that it is not necessary to define a type for the variable.
So it’s like you said:
it creates the type of variable at startup of the same
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 such as is_string
, is_float
, is_int
and is_boolean
.
You can also get the variable type name 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 of a certain instance or subinstication. If it implements an interface, if it is a callback, or if it is an array.
Examples of type induction for classes:
class X{
public function get(){}
}
function usa_x(X $x){
return $x->get();
}
usa_x(new X);
Examples of type induction for arrays:
function usa_array(array $array){
foreach($array as $key => $value);
}
usa_array(1); // gera um erro!
Examples of type induction for callbacks (from 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’s an extension called Spl Type
, where it is possible to simulate the definition of types 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 believe in most cases it is not), here is the link to Spltype
Have a look at http://php.net/manualen/language.oop5.typehinting.php
– lazyFox
I don’t understand ....
– Vynstus
I think that "Vista de olhos" in Portuguese is to "take a look" at Nrasil
– Wallace Maxters
I did not understand the content of the last link ... I could not relate to my question
– Vynstus