What would be the best way to check the type of an array in PHP?
Lets say I have the following:
class Toggler
{
protected $devices;
public function __construct(array $devices)
{
$this->devices = $devices;
}
public function toggleAll()
{
foreach ($this->devices as $device)
{
$device->toggle();
}
}
}
What happens here is simple: The Toggler
class requires an array of 'Devices', loops over those devices and calls the toggle()
method on them.
What I want however, is that the array of devices must contain only objects that implement the Toggleable
interface (which would tell the object to supply a toggle()
method).
Now I can't do something like this, right?
class Toggler
{
protected $devices;
public function __construct(Toggleable $devices)
{
$this->devices = $devices;
}
public function toggleAll()
{
foreach ($this->devices as $device)
{
$device->toggle();
}
}
}
As far as I know you can't typehint an array as an array in PHP has no type (unlike languages like C++).
Would you instead have to check type in the loop for each device? And throw an exception? What would be the best thing to do?
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();
}
}
}
Is there a better, cleaner, way to do this? I figured as I was writing this pseudo code you would also need to check if the device is an object at all (else you can't do get_class($device)
).
Any help would be appreciated.