2017-04-13 36 views
1

在PHP中检查数组类型的最佳方法是什么?PHP类型提示对象数组

可以说我有以下几点:

class Toggler 
{ 

    protected $devices; 

    public function __construct(array $devices) 
    { 
     $this->devices = $devices; 
    } 

    public function toggleAll() 
    { 
     foreach ($this->devices as $device) 
     { 
      $device->toggle(); 
     } 
    } 

} 

这里会发生什么事很简单:Toggler类需要“设备”的数组,循环遍历这些设备并调用toggle()方法上他们。

然而,我想要的是,设备阵列必须只包含实现Toggleable接口(它会告诉对象提供一个toggle()方法)的对象。

现在我不能这样做,对吧?

class Toggler 
{ 

    protected $devices; 

    public function __construct(Toggleable $devices) 
    { 
     $this->devices = $devices; 
    } 

    public function toggleAll() 
    { 
     foreach ($this->devices as $device) 
     { 
      $device->toggle(); 
     } 
    } 

} 

据我所知你不能在PHP中输入数组作为数组没有类型(与C++之类的语言不同)。

你需要检查每个设备的循环类型吗?并抛出异常?什么是最好的事情?

class Toggler 
{ 

    protected $devices; 

    public function __construct(array $devices) 
    { 
     $this->devices = $devices; 
    } 

    public function toggleAll() 
    { 
     foreach ($this->devices as $device) 
     { 
      if (! $device instanceof Toggleable) { 
       throw new \Exception(get_class($device) . ' is not does implement the Toggleable interface.'); 
      } 

      $device->toggle(); 
     } 
    } 

} 

有没有更好,更清洁的方法来做到这一点?我想,当我写这个伪代码时,你还需要检查设备是否是一个对象(否则你不能做get_class($device))。

任何帮助,将不胜感激。

+0

http://stackoverflow.com/a/34273821/1848929 – hakiko

+0

看起来您已经找到了解决方案。作为一种改进,我会在'$ this-> devices'设置(即在构造函数中)时执行'instanceof'验证,这有两个好处:尽快找到'Toggler'类的任何错误用法,并确保'Toggler'类是有效的。另外,还有一点小小的性能改进:构造函数只被调用一次,另一种方法可能会被调用很多次。 – axiac

+0

@hakiko我正确地说'toggleAll()'会为数组中的每个项目调用一个'toggle(Toggler $ toggler)'?我喜欢过度复杂的问题lmao –

回答

3

一种选择(需要PHP> = 5.6.0)是定义方法

public function __construct(Toggleable ...$devices) 

但你将不得不使用阵列打包/解包的两侧;构造函数以及实例化对象的位置,例如

$toggleAbles = [new Toggleable(), new Toggleable()]; 
$toggler = new Toggler(...$toggleAbles); 
+0

该死的聪明,似乎是解决问题的最短最优雅的方式。你认为这是比问题更好的解决方案:http://stackoverflow.com/questions/34273367/type-hinting-in-php-7-array-of-objects/34273821#34273821?如果稍后有人忘记拆开设备阵列并插入整个阵列,会是一个问题吗? –

+0

如果有人忘记在实例化Toggler之前解压数组,那么你会得到一个传递给构造函数的数组,根据'Toggleable' typehint将会失效,并且会得到一个可恢复的致命错误或TypeError异常(取决于PHP的版本) –

+0

打包的参数也必须是函数/构造函数定义中的最后一个参数,这是另一个限制 –