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);
}
4
  • 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, 2020 at 2:20
  • 1
    PHP 5.4 was end of life and support over 5 years ago. Dec 24, 2020 at 2: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, 2020 at 2: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, 2020 at 2:30

1 Answer 1

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.

1
  • Thanks John. I have a dev account with cPanel. Already upgraded to 7.3 based on feedback.
    – jacekn
    Dec 24, 2020 at 2:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.