简体   繁体   中英

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

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:

  • a class or interface;
  • self ;
  • array (without any specifics as to its contents);
  • callable;
  • bool;
  • float;
  • int;
  • string

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM