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)
Some functions are designed to return values, while others are designed for other purposes. We pass arguments in a function, we can pass no arguments at all, single arguments or multiple arguments to a function and can call the function multiple times.
PHP native functions According to the manual, PHP functions may accept up to 12 arguments.
5 Types of Arguments in Python Function Definition: keyword arguments. positional arguments. arbitrary positional arguments. arbitrary keyword arguments.
We use variable-length arguments if we don't know the number of arguments needed for the function in advance. Types of Arbitrary Arguments: arbitrary positional arguments ( *args ) arbitrary keyword arguments ( **kwargs )
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;
}
}
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){}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With