20

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)

yivi
  • 42,438
  • 18
  • 116
  • 138
Swader
  • 11,387
  • 14
  • 50
  • 84
  • Does this answer your question? [Is it possible to type hint more than one type?](https://stackoverflow.com/questions/46775489/is-it-possible-to-type-hint-more-than-one-type) – yivi Feb 27 '20 at 10:34

4 Answers4

41

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;
    }
}
ShaneOH
  • 1,454
  • 1
  • 17
  • 29
3

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){}
Pauly
  • 299
  • 1
  • 6
2

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.

Palantir
  • 23,820
  • 10
  • 76
  • 86
  • 1
    Cheers, I finally know it's called Type Hinting now. – Swader Oct 24 '11 at 09:17
  • 1
    It's called Hinting in PHP (only?) because it is in fact just a hint for the PHP interpreter, which is thus instructed to "artificially" check the argument type and throw an error if it does not match with the hint. In statically typed languages it is a basic and required thing, part of the syntax for functions, and it is not called like that... in fact I don't think it has a specific name otherwise... – Palantir Oct 24 '11 at 12:14
0

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

symcbean
  • 47,736
  • 6
  • 59
  • 94