Be careful comparing ReflectionParameter::getType() and gettype() as they will not return the same results for a given type.
string - string // OK
int - integer // Type mismatch
bool - boolean // Type mismatch
array - array // OK
(PHP 4, PHP 5, PHP 7, PHP 8)
gettype — Obtém o tipo de uma variável
Retorna o tipo da variável PHP value
. Para
checagem de tipo, utilize as funções is_*
.
value
A variável a ter o tipo verificado.
Os valores possíveis para a string retornada são:
"boolean"
- booleano
"integer"
- inteiro
"double"
- ponto flutuante (por razões históricas, "double"
é
retornado no caso de um float, e não simplesmente
"float"
)
"string"
- cadeia de caracteres
"array"
"object"
- objeto
"resource"
- recurso
"resource (closed)"
a partir do PHP 7.2.0 - recurso (fechado)
"NULL"
- nulo
"unknown type"
- tipo desconhecido
Versão | Descrição |
---|---|
7.2.0 |
Recursos já fechados agora são reportados como 'resource (closed)' .
Anteriormente os valores retornados para recursos fechados eram 'unknown type' .
|
Exemplo #1 Exemplo da função gettype()
<?php
$data = array(1, 1., NULL, new stdClass, 'foo');
foreach ($data as $value) {
echo gettype($value), "\n";
}
?>
O exemplo acima produzirá algo semelhante a:
integer double NULL object string
Be careful comparing ReflectionParameter::getType() and gettype() as they will not return the same results for a given type.
string - string // OK
int - integer // Type mismatch
bool - boolean // Type mismatch
array - array // OK
Since ReflectionParameter::getType() and gettype() do not return the same type name, you can leverage the strpos() function.
use DateTime;
use ReflectionClass;
$myVar = 45;
# get the type of your variable
$varType = gettype($myVar);
$cls = new ReflectionClass(DateTime::class);
$mth = $cls->getMethod('setDate');
$params = $mth->getParameters();
foreach($params as $param) {
$paramTypes = $param instanceof ReflectionUnionType
? $param->getTypes()
: [$param];
foreach($paramTypes as $paramType) {
if (strpos($paramType, $varType) >= 0) {
echo "Parameter '". $paramType->getName() ."' has type '". $paramType->getType() ."' which matches the variable's type of '$varType'.\n";
}
}
}