1

Java compiler ensures that each method call includes arguments compatible with parameter types. In the example below, passing something that does not implement LogService interface won't even compile.

public logMessage(LogService logService, String message) {
    logService.logMessage(message);
}

Is there a way to achieve the same with PHP? If I pass an object that is not compatible with LogService interface, I'd like to know that immediately in IDE, rather than find out in testing. I'm currently using PHP 5.4 but I have options to go higher.

public function logMessage($logService, $message) {
    $logService->logMessage($message);
}
John Conde
  • 217,595
  • 99
  • 455
  • 496
jacekn
  • 1,521
  • 5
  • 29
  • 50
  • 4
    Upgrade to a version of PHP that supports parameter type declarations (PHP 7). In fact, go to 7.3 or higher since that is what is currently supported. You'll get a nice performance boost, too. – John Conde Dec 24 '20 at 02:20
  • 1
    PHP 5.4 was end of life and support over 5 years ago. – AbraCadaver Dec 24 '20 at 02:22
  • Yeah, I realize I should be looking past 5.4. I've just started to code something in PHP after years of not working with this technology and I'm just trying to remember how to do things before I actually consider any implementation. But basically you're telling me that I 'm wasting my time with 5.4... – jacekn Dec 24 '20 at 02:28
  • John, in my own search I didn't even come across the term 'hinting'. I see that it pretty much answers my question. Please put together an answer post. – jacekn Dec 24 '20 at 02:30

1 Answers1

1

PHP 7 introduced type declarations which allows you to do what you showed in your Java example. If you use declare(strict_types=1); PHP will throw a Fatal error if the parameter type does not match the function signature. If that is omitted it will attempt to type cast the value to that type (much like when using the == comparison operator vs the strict === comparison operator).

public function logMessage(LogService $logService, string $message) {
    $logService->logMessage($message);
}

I recommend using the latest versions of PHP to not only ensure you have the latest security patches but also gain the latest functionality. For example, nullable parameter types wasn't introduced until PHP 7.1, object types in 7.2, and union types in 8.0.

John Conde
  • 217,595
  • 99
  • 455
  • 496