我们如何在 PHP 中强制执行参数类型?
How do we enforce parameter types in PHP?
Java 编译器确保每个方法调用都包含与参数类型兼容的参数。在下面的示例中,传递未实现 LogService 接口的内容甚至不会编译。
public logMessage(LogService logService, String message) {
logService.logMessage(message);
}
有没有办法实现与 PHP 相同的效果?如果我传递一个与 LogService 接口不兼容的对象,我想立即在 IDE 中知道,而不是在测试中发现。我目前使用的是 PHP 5.4,但我可以选择更高版本。
public function logMessage($logService, $message) {
$logService->logMessage($message);
}
PHP 7 introduced type declarations 允许您执行在 Java 示例中显示的内容。如果使用 declare(strict_types=1);
PHP 如果参数类型与函数签名不匹配,将抛出致命错误。如果省略它,它将尝试将值类型转换为该类型(很像使用 ==
比较运算符与严格的 ===
比较运算符)。
public function logMessage(LogService $logService, string $message) {
$logService->logMessage($message);
}
我建议使用最新版本的 PHP,这样不仅可以确保您拥有最新的安全补丁,还可以获得最新的功能。例如,可空参数类型不是 introduced until PHP 7.1, object
types in 7.2, and union types in 8.0.
Java 编译器确保每个方法调用都包含与参数类型兼容的参数。在下面的示例中,传递未实现 LogService 接口的内容甚至不会编译。
public logMessage(LogService logService, String message) {
logService.logMessage(message);
}
有没有办法实现与 PHP 相同的效果?如果我传递一个与 LogService 接口不兼容的对象,我想立即在 IDE 中知道,而不是在测试中发现。我目前使用的是 PHP 5.4,但我可以选择更高版本。
public function logMessage($logService, $message) {
$logService->logMessage($message);
}
PHP 7 introduced type declarations 允许您执行在 Java 示例中显示的内容。如果使用 declare(strict_types=1);
PHP 如果参数类型与函数签名不匹配,将抛出致命错误。如果省略它,它将尝试将值类型转换为该类型(很像使用 ==
比较运算符与严格的 ===
比较运算符)。
public function logMessage(LogService $logService, string $message) {
$logService->logMessage($message);
}
我建议使用最新版本的 PHP,这样不仅可以确保您拥有最新的安全补丁,还可以获得最新的功能。例如,可空参数类型不是 introduced until PHP 7.1, object
types in 7.2, and union types in 8.0.