PHP Conference Japan 2024

ReflectionProperty::getType

(PHP 7 >= 7.4.0, PHP 8)

ReflectionProperty::getType取得屬性的類型

說明

public ReflectionProperty::getType(): ?ReflectionType

取得屬性的關聯類型。

參數

此函式沒有參數。

回傳值

如果屬性具有類型,則返回 ReflectionType,否則返回 null

範例

範例 #1 ReflectionProperty::getType() 範例

<?php
class User
{
public
string $name;
}

$rp = new ReflectionProperty('User', 'name');
echo
$rp->getType()->getName();
?>

以上範例會輸出

string

另請參閱

新增註解

使用者貢獻的註解 1 則註解

6
email at dronov dot vg
4 年前
類別 User
{
/**
* @var string
*/
public $name;
}

函式 getTypeNameFromAnnotation(字串 $className, 字串 $propertyName): ?字串
{
$rp = new \ReflectionProperty($className, $propertyName);
如果 (preg_match('/@var\s+([^\s]+)/', $rp->getDocComment(), $matches)) {
返回 $matches[1];
}

返回 null;
}

echo getTypeNameFromAnnotation('User', 'name');

// string
To Top