PHP 类型提示对象数组
PHP type hinting array of objects
在 PHP 中检查数组类型的最佳方法是什么?
假设我有以下内容:
class Toggler
{
protected $devices;
public function __construct(array $devices)
{
$this->devices = $devices;
}
public function toggleAll()
{
foreach ($this->devices as $device)
{
$device->toggle();
}
}
}
这里发生的事情很简单:Toggler
class 需要一个 'Devices' 数组,遍历这些设备并调用它们的 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)
)。
如有任何帮助,我们将不胜感激。
一个选项(需要 PHP >= 5.6.0)是将方法定义为
public function __construct(Toggleable ...$devices)
但是你必须在两边都使用数组packing/unpacking;构造函数以及实例化对象的任何地方,例如
$toggleAbles = [new Toggleable(), new Toggleable()];
$toggler = new Toggler(...$toggleAbles);
在 PHP 中检查数组类型的最佳方法是什么?
假设我有以下内容:
class Toggler
{
protected $devices;
public function __construct(array $devices)
{
$this->devices = $devices;
}
public function toggleAll()
{
foreach ($this->devices as $device)
{
$device->toggle();
}
}
}
这里发生的事情很简单:Toggler
class 需要一个 'Devices' 数组,遍历这些设备并调用它们的 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)
)。
如有任何帮助,我们将不胜感激。
一个选项(需要 PHP >= 5.6.0)是将方法定义为
public function __construct(Toggleable ...$devices)
但是你必须在两边都使用数组packing/unpacking;构造函数以及实例化对象的任何地方,例如
$toggleAbles = [new Toggleable(), new Toggleable()];
$toggler = new Toggler(...$toggleAbles);