Reputation: 11597
Is it possible to define a function argument as multiple possible types? For example, a function may take a string or an integer to accomplish something. Is it possible to somehow define it like this?
function something(int|string $token) {}
Or is only one type per argument supported?
(mind you, I know I can filter input later on, I just like to have my arguments typed)
Upvotes: 24
Views: 31424
Reputation: 1555
Union types have finally been implemented in PHP 8.0, which is due for release near the end of 2020.
They can be used like this:
class Number {
private int|float $number;
public function setNumber(int|float $number): void {
$this->number = $number;
}
public function getNumber(): int|float {
return $this->number;
}
}
Upvotes: 47
Reputation: 299
No, it is not possible.
Also, type hinting in PHP 5 is now only for classes and arrays. http://php.net/manual/en/language.oop5.typehinting.php
class Foo
{
}
function something(Foo $Object){}
Upvotes: 3
Reputation: 48357
PHP is dynamically typed - but type hinting has been added to the language - so if you've not hinted the parameter you can pass any type you like:
function something($token)
{
if (is_numeric($token)) {
// its a float, double, integer
} else {
// its a string, array, object
}
}
(off the top of my head I'm not sure how resources are handled).
However if you want to program in a strongly typed language, then (IMHO) you should be using something other than PHP
Upvotes: 0
Reputation: 24182
The best you can do is called Type Hinting and is explained here:
http://php.net/manual/en/language.oop5.typehinting.php
In particular, you can hint a class type or an array type, but (as the manual says) "Traditional type hinting with int and string isn't supported." So I guess that what you are trying to accomplish is not possible at this level.
However, you can create your own wrappers, etc. There are probably a thousand ways to handle this.
Upvotes: 2