在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)
)。
任何帮助,将不胜感激。
http://stackoverflow.com/a/34273821/1848929 – hakiko
看起来您已经找到了解决方案。作为一种改进,我会在'$ this-> devices'设置(即在构造函数中)时执行'instanceof'验证,这有两个好处:尽快找到'Toggler'类的任何错误用法,并确保'Toggler'类是有效的。另外,还有一点小小的性能改进:构造函数只被调用一次,另一种方法可能会被调用很多次。 – axiac
@hakiko我正确地说'toggleAll()'会为数组中的每个项目调用一个'toggle(Toggler $ toggler)'?我喜欢过度复杂的问题lmao –