2016-08-01 65 views
1

我使用Laravel 5.2,我想創建一個方法,其中參數必須是Foo,Bar或者Baz的一個實例。如果參數不是這些類中的任何一個的對象,則拋出一個錯誤。動態參數

App\Models\Foo; 
App\Models\Bar; 
App\Models\Baz; 


public function someMethod(// what to type hint here??) 
{ 
    // if 1st argument passed to someMethod() is not an object of either class Foo, Bar, Baz then throw an error 
} 

如何做到這一點?

回答

3

您可以同時使用類名稱和接口類型提示,但前提是所有3類擴展同一個類或實現相同的接口,否則你將不能夠這樣做:

class C {} 
class D extends C {} 

function f(C $c) { 
    echo get_class($c)."\n"; 
} 

f(new C); 
f(new D); 

這還將連續工作接口:

interface I { public function f(); } 
class C implements I { public function f() {} } 

function f(I $i) { 
    echo get_class($i)."\n"; 
} 

f(new C); 
+0

考慮到您可以實現多個接口,我相信最佳實踐是實現像Dekel所展示的接口。 – Nitin

+0

@Nitin基於單一方法的輸入需求來構造你的類遠非最佳實踐。當然有很多這種方法適用的情況。 – rjdown

+0

優秀的界面使用,我喜歡。 –

5

有沒有辦法來提供你想要的方式多類型提示(除非它們擴展/實現相互按德克爾的答案)。

您將需要手動執行的類型,例如:

/** 
* Does some stuff 
* 
* @param Foo|Bar|Baz $object 
* @throws Exception 
*/ 
+0

從我得到+1 :) – Dekel

+0

同樣,所有有用的東西 – rjdown

1

「:

public function someMethod($object) { 
    if (!in_array(get_class($object), array('Foo', 'Bar', 'Baz'))) { 
     throw new Exception('ARGGH'); 
    } 
} 

可以通過提供所需類型的列表作爲PHPDoc的提示幫助最終用戶有所不支持多個「typehinting」。

簡單的辦法就是用instanceof(或@rjdown溶液)檢查

public function someMethod($arg) 
{ 
    if (!$arg instanceof Foo && !$arg instanceof Bar && !$arg instanceof Bar) { 
     throw new \Exception("Text here") 
    } 
} 

或者讓你的類implement一些interface。例如:

class Foo implements SomeInterface; 
class Bar implements SomeInterface; 
class Baz implements SomeInterface; 

// then you can typehint: 
public function someMethod(SomeInterface $arg)