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.
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.
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.
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);
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');
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