Skip to content

Core\Reflect\ParameterInfo::type

$parameterInfo->type(): ?string

Returns the declared type of one parameter of a method, as text.

type() returns the type written the same way the method writes it: int, ?int for an int that may be null, array<string>, or the name of a class. A parameter declared in a source file always has a type, so the result is text. The result is null only if no type is known.

The result is the text of the declaration. It is not a value you can check a value against. To check the type of a value, use Core\Reflect::typeOf.

The examples below print the type of each parameter, show nullable, array and class types, and write the help text for a web API from the parameters of its handler.

Return value

Returns ?string. The type as text, such as int, ?int, array<string> or App\User. A parameter declared in a source file always has a type, so the result is text. The result is null only if no type is known for the parameter. To check the type of a value, use Core\Reflect::typeOf.

Examples

Print the type of each parameter

<?nvs
// Shows how to print the declared type of each parameter of a method.
class Cart
{
public function add(string $sku, uint $quantity, float $price): void
{}
}
foreach (Core\Reflect::forObject(new Cart())->methods() as Core\Reflect\MethodInfo $method) {
foreach ($method->parameters() as Core\Reflect\ParameterInfo $parameter) {
// This prints `sku: string`, `quantity: uint` and `price: float`.
echo $parameter->name(), ': ', $parameter->type() ?? 'unknown', "\n";
}
}
Output
sku: string
quantity: uint
price: float

Nullable array and class types

<?nvs
// Shows that `type` returns a nullable type, an array type and a class name exactly as they are written.
class Customer
{}
class Orders
{
public function find(?int $limit, array<string> $tags, Customer $owner): void
{}
}
foreach (Core\Reflect::forObject(new Orders())->methods() as Core\Reflect\MethodInfo $method) {
foreach ($method->parameters() as Core\Reflect\ParameterInfo $parameter) {
// This prints `?int`, then `array<string>`, then `Customer`.
echo $parameter->type() ?? 'unknown', "\n";
}
}
Output
?int
array<string>
Customer

Write help for a web api

<?nvs
// Shows how to write the help text of a web API from the parameters of its handler method.
class SearchHandler
{
public function handle(string $query, ?int $page, ?string $sort): string
{
return $query;
}
}
echo "GET /search\n";
foreach (Core\Reflect::forObject(new SearchHandler())->methods() as Core\Reflect\MethodInfo $method) {
foreach ($method->parameters() as Core\Reflect\ParameterInfo $parameter) {
string $type = $parameter->type() ?? 'string';
// A type that starts with `?` may be `null`, so the field is optional.
if (Core\Str::startsWith($type, '?')) {
echo ' ', $parameter->name(), ' (', $type, ", optional)\n";
} else {
echo ' ', $parameter->name(), ' (', $type, ", required)\n";
}
}
}
Output
GET /search
query (string, required)
page (?int, optional)
sort (?string, optional)