2016-02-11 31 views

回答

1

不,因爲它不可能在PHP中。 PHP5類型提示僅適用於函數和方法參數,但不適用於返回類型。

然而,PHP7增加返回類型聲明但是,類似參數類型聲明,他們只能是以下之一:

  • 一個類或接口;
  • self;
  • 數組(沒有關於其內容的任何細節);
  • callable;
  • bool;
  • float;
  • int;

如果您使用PHP7,您可以指定只是一個數組或創建一個能夠容納這兩個對象,並使用它作爲返回類型的類。

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

0

這適用於phpstorm(沒有指定的元素順序ofcourse):

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

簡短的回答是沒有

稍長的答案是,您可以創建自己的Value Object作爲提示,但這意味着您將需要返回一個對象而不是數組。

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

注意:這需要PHP 7以提示返回類型。

相關問題