Defining multiple function argument types in PHP

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.


2020 Update:

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){}

Tags:

Php

Function