I want to
return array(new Foo(), new Bar());
is there a way I can do type hinting for that?
The short answer is no.
The slightly longer answer is that you can create your own Value Object to use as the hint, but this means that you will need to return an object instead of an array.
class Foo {};
class Bar {};
class Baz {
private $foo;
private $bar;
public function __construct(Bar $bar, Foo $foo) {
$this->bar = $bar;
$this->foo = $foo;
}
public function getFoo() : Foo {
return $this->foo;
}
public function getBar() : Bar {
return $this->bar;
}
}
function myFn() : Baz {
return new Baz(new Bar(), new Foo());
}
$myObj = myFn();
var_dump($myObj);
Note: this requires PHP 7+ for hinting return types.
No, as such it is not possible in PHP. PHP5 type hinting is for function and method arguments only but not return types.
However, PHP7 adds return type declarations but, similar to argument type declarations, they can only be one of:
self
;If you're using PHP7, you can either specify just an array or create a class that would hold those two objects and use that as return type.
http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
http://php.net/manual/en/functions.returning-values.php#functions.returning-values.type-declaration
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