jacekn
jacekn

Reputation: 1541

How do we enforce parameter types in PHP?

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);
}

Upvotes: 1

Views: 439

Answers (1)

John Conde
John Conde

Reputation: 219804

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.

Upvotes: 1

Related Questions