动态参数
问题描述:
我使用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类扩展同一个类或实现相同的接口,否则你将不能够这样做:
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);
答
“:
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)
考虑到您可以实现多个接口,我相信最佳实践是实现像Dekel所展示的接口。 – Nitin
@Nitin基于单一方法的输入需求来构造你的类远非最佳实践。当然有很多这种方法适用的情况。 – rjdown
优秀的界面使用,我喜欢。 –