3v4l.org

run code in 300+ PHP versions simultaneously
<?php interface Vehicle { public function setSpeedLimit(Float $limit) : Car; public function setManufacturer(String $manufacturer) : MethodOfTransport; } interface NonVehicle { public function addSaddle() : Bicycle; public function setManufacturer(String $manufacturer) : MethodOfTransport; } abstract class MethodOfTransport { public function setManufacturer(String $manufacturer) : MethodOfTransport { return $this; } } class Bicycle extends MethodOfTransport implements NonVehicle { public function addSaddle() : Bicycle { return $this; } } class Car extends MethodOfTransport implements Vehicle { public function setSpeedLimit(Float $limit) : Car { return $this; } } $b = (new Bicycle())->setManufacturer( 'Foo' )->addSaddle(); $c = (new Car())->setManufacturer( 'Bar' )->setSpeedLimit( 140 ); interface VehicleServiceInterface { public function create(MethodOfTransport $t) : Void; } class VehicleService implements VehicleServiceInterface { public function create(MethodOfTransport $t) : Void { if (!$t instanceof Vehicle) throw new Exception( 'Cannot create a Vehicle on a NonVehicle instance.' ); echo 'Created'; } } (new VehicleService())->create( $c ); // Works (new VehicleService())->create( $b ); // Throws Exception
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.31, 8.2.0 - 8.2.26, 8.3.0 - 8.3.14, 8.4.1
Created Fatal error: Uncaught Exception: Cannot create a Vehicle on a NonVehicle instance. in /in/ccumv:41 Stack trace: #0 /in/ccumv(48): VehicleService->create(Object(Bicycle)) #1 {main} thrown in /in/ccumv on line 41
Process exited with code 255.

preferences:
83.74 ms | 407 KiB | 5 Q