gpt4 book ai didi

PHP 类型提示对象数组

转载 作者:行者123 更新时间:2023-12-02 20:48:08 27 4
gpt4 key购买 nike

在 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 的对象接口(interface)(它会告诉对象提供 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)

但是你必须在两侧使用数组打包/解包;构造函数以及实例化对象的位置,例如

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

关于PHP 类型提示对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43399282/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com