How to make hinting type for an array of specific objects in php?

I want to

return array(new Foo(), new Bar()); 

is there any way i can do for this hint?

+5
source share
3 answers

The short answer is no.

A slightly longer answer is that you can create your own Value object to use as a hint, but that means you will need to return the 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+ to prompt return types.

+3
source

No, how is this impossible in PHP. The PHP5 type hint is only for function and method arguments, but not for return types.

However, PHP7 adds declarations of type of return type, but, like declarations of type of argument, they can be only the following:

  • class or interface;
  • self ;
  • (without any features of its contents);
  • called up;
  • BOOL;
  • float;
  • INT
  • line

If you are using PHP7, you can only specify an array or create a class that will contain these two objects and use this as the 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

+1
source

This works in phpstorm (without specifying the order of the elements):

 /** * @return Foo[]|Bar[] */ 
0
source

Source: https://habr.com/ru/post/1242779/


All Articles