2016-02-11 7 views

risposta

1

No, come tale non è possibile in PHP. L'hint di tipo PHP5 è solo per argomenti di funzioni e metodi, ma non per tipi di ritorno.

Tuttavia, PHP7 aggiunge ritorno dichiarazioni di tipo ma, simile a dichiarazioni di tipo argomento, possono essere solo uno:

  • una classe o interfaccia;
  • self;
  • array
  • (senza alcuna specifica sul suo contenuto);
  • richiamabile;
  • bool;
  • galleggiante;
  • int;
  • stringa

Se stai usando PHP7, è possibile specificare solo un array o creare una classe che terrebbe questi due oggetti e l'uso che come tipo di ritorno.

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

Questo funziona in PhpStorm (senza ordine di elementi specificando ofcourse):

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

La risposta breve è no .

La risposta leggermente più lunga è che è possibile creare il proprio Value Object da utilizzare come suggerimento, ma ciò significa che sarà necessario restituire un oggetto anziché un 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); 

Nota: questo richiede PHP 7+ per suggerire tipi di ritorno.

Problemi correlati