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 — Bir değişkenin türünü döndürür
Belirtilen değişkenin türünü döndürür. Türü sınamak için
is_*
işlevleri kullanılmalıdır.
değişken
Türüne bakılacak değişken.
Olası dönüş değerleri:
"boolean"
"integer"
"double"
(tarihsel sebeplerle float
durumunda "double" döndürülür)
"string"
"array"
"object"
"resource"
"resource (closed)"
PHP 7.2.0 ve sonrası
"NULL"
"unknown type"
Sürüm: | Açıklama |
---|---|
7.2.0 |
Kapalı özkaynaklar için artık 'resource (closed)'
dönüyor. Evvelce bu durumda 'unknown type'
dönerdi.
|
Örnek 1 - gettype() örneği
<?php
$data = array(1, 1., NULL, new stdClass, 'foo');
foreach ($data as $value) {
echo gettype($value), "\n";
}
?>
Yukarıdaki örnek şuna benzer bir çıktı üretir:
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";
}
}
}