本文介绍了PHP:常量作为函数中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用常量作为函数参数,是否可以检查此常量的类型。
I'm trying to use constant as a function paramter, is it possible to check type of this constant.
我想要的示例:
class ApiError {
const INVALID_REQUEST = 200;
}
class Response {
public function status(ApiError $status) {
//function code here
}
}
使用情况:
$response = new Response();
$response->status(ApiError::INVALID_REQUEST);
此应检查的是,给定的$ status是类ApiError的常量。
This shoud check that given $status is constant of class ApiError. Is something like this possible?
推荐答案
正如其他提到的那样,没有通用的解决方案。但是,如果您想以一种非常干净的方式进行操作,则可以对要处理的每个对象进行建模(=每个可能的状态),例如:
As the others mentioned, there is no generic solution. But if you'd like to do it in a very clean way, model every "object" that you're dealing with (= every possible status), e.g.:
interface ApiError { // make it an abstract class if you need to add logic
public function getCode();
}
class InvalidRequestApiError implements ApiError {
public function getCode() {
return 200;
}
}
// Usage:
$response = new Response();
$response->status( new InvalidRequestApiError() );
class Response {
public function status(ApiError $status) {
echo "API status: " . $status->getCode();
}
// ...
}
您拥有很多类,因为您封装了简单的数字,而且还具有键入提示的功能。
This leaves you with a lot of classes, because you encapsulate simple numbers, but also with the ability to type-hint.
这篇关于PHP:常量作为函数中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!