简体   繁体   English

我们如何在 PHP 中强制执行参数类型?

[英]How do we enforce parameter types in PHP?

Java compiler ensures that each method call includes arguments compatible with parameter types. Java编译器确保每个方法调用都包含与参数类型兼容的arguments。 In the example below, passing something that does not implement LogService interface won't even compile.在下面的示例中,传递不实现 LogService 接口的东西甚至不会编译。

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

Is there a way to achieve the same with PHP?有没有办法用 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.如果我通过一个与LogService接口不兼容的object,我想立即在IDE中知道,而不是在测试中发现。 I'm currently using PHP 5.4 but I have options to go higher.我目前正在使用 PHP 5.4,但我可以选择更高的 go。

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

PHP 7 introduced type declarations which allows you to do what you showed in your Java example. PHP 7 引入了类型声明,允许您执行您在 Java 示例中显示的内容。 If you use declare(strict_types=1);如果你使用declare(strict_types=1); PHP will throw a Fatal error if the parameter type does not match the function signature.如果参数类型与 function 签名不匹配,PHP 将引发致命错误。 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.我建议使用最新版本的 PHP,不仅可以确保您拥有最新的安全补丁,还可以获得最新的功能。 For example, nullable parameter types wasn't introduced until PHP 7.1 , object types in 7.2 , and union types in 8.0 .例如,可空参数类型直到 PHP 7.1 才引入object类型在 7.2中, 联合类型在 8.0 中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM