Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to specify more than one type hint for a parameter? [duplicate]

Tags:

Is there a way to add more than one type hinting to a method? For example, foo(param) must receive a instance of string OR bar OR baz.

like image 358
joao Avatar asked Oct 01 '10 14:10

joao


People also ask

Can a python function return multiple types?

Practical Data Science using PythonPython functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.

What is type hinting in PHP?

Type hinting is a concept that provides hints to function for the expected data type of arguments. For example, If we want to add an integer while writing the add function, we had mentioned the data type (integer in this case) of the parameter.


2 Answers

That is not possible to enforce (except inside the method). You can only provide a single type hint, and only to objects/interfaces and arrays (since PHP 5.1).

You can/should however document it in your method, i.e:

/**
 * @param string|Bar|Baz $param1
 */
function foo($param1);
like image 98
PatrikAkerstrand Avatar answered Oct 18 '22 22:10

PatrikAkerstrand


This is one use of interfaces. If you want to be sure that the object has a ->foobar($baz) method, you could expect an interface:

interface iFooBar {
    public function foobar($baz);
}

class Foo implements iFooBar {
    public function foobar($baz) { echo $baz; }
}
class Bar implements iFooBar {
    public function foobar($baz) { print_r($baz); }
}

function doSomething(iFooBar $foo) {
    $foo->foobar('something');
}

Then, when calling, these will work:

doSomething(new Foo());
doSomething(new Bar());

These will not:

doSomething(new StdClass());
doSomething('testing');
like image 21
ircmaxell Avatar answered Oct 18 '22 20:10

ircmaxell