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 — Liefert den Datentyp einer Variablen
Liefert den Datentyp der Variablen value
. Zur
Typprüfung sollten die is_*
Funktionen verwendet
werden.
value
Die Variable, deren Typ ermittelt werden soll.
Mögliche Werte der zurückgegebenen Zeichenkette sind:
Version | Beschreibung |
---|---|
7.2.0 |
Geschlossene Ressourcen werden nun als 'resource
(closed)'
gemeldet. Zuvor war der Rückgabewert für geschlossene Ressourcen
'unknown type' .
|
Beispiel #1 gettype()-Beispiel
<?php
$data = array(1, 1., NULL, new stdClass, 'foo');
foreach ($data as $value) {
echo gettype($value), "\n";
}
?>
Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:
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";
}
}
}