Lack of class casting leads to inspection message. How to avoid (in code)?
Hi @ all,
my code is calling a method, which is hidden by downcasting. This works well with PHP, would not work in strong casting languages like C++, and produces a message by the PhpStorm Inspector. Since there is no explicit object casting in PHP, what is the best practice for this kind of code? Just using /** @noinspection PhpUndefinedMethodInspection */ ? Or did I miss any kind of casting?
A (very simple and untested) example code is here:
class Car {
public function speedUp() {;}
}
class Hybrid extends Car {
public function startFuelMode() {;}
}
function moveCar(Car $car) { //downcast to have a general method
if ($car instanceof Hybrid) {
$car->startFuelMode(); // PhpStorm Inspector -> Method 'startFuelMode' not found in class
}
$car->speedUp();
}
$myHybrid = new Hybrid();
moveCar($myHybrid); // $myHybrid is downcasted to Car
One solution in C++ (with PHP syntax) would be:
//$car->startFuelMode(); // PhpStorm Inspector -> Method 'startFuelMode' not found in class
((Car)$car)->startFuelMode();
Any comments are appreciated.
I use PhpStorm 6.0.3
Cheers
Patrick
请先登录再写评论。
Hi there,
Please try v7 -- it shows no warning there using your sample code. v7 has some improvements made when handling such construction ( if ($VAR instanceof SOME_CLASS) { ... )