I'm trying to use constant as a function paramter, is it possible to check type of this constant.
Example of what I want:
class ApiError {
const INVALID_REQUEST = 200;
}
class Response {
public function status(ApiError $status) {
//function code here
}
}
USE:
$response = new Response();
$response->status(ApiError::INVALID_REQUEST);
This shoud check that given $status is constant of class ApiError. Is something like this possible?
Constants Declared with define() are Global Constants that are declared using the define() function become globally available to the current PHP script. You can even use it within functions and classes.
Syntax ¶ Constants can be defined using the const keyword, or by using the define()-function. While define() allows a constant to be defined to an arbitrary expression, the const keyword has restrictions as outlined in the next paragraph. Once a constant is defined, it can never be changed or undefined.
Checking if a PHP Constant is Defined This can be achieved using the PHP defined() function. The defined() function takes the name of the constant to be checked as an argument and returns a value of true or false to indicate whether that constant exists.
Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.
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.
You can use in_array()
to test against whitelisted values, which is a recommended strategy whenever you need to validate input to a specific value set:
// Test if it is in an array of valid status constants...
$valid_statuses = array(
ApiError::INVALID_REQUEST,
ApiError::INVALID_SOMETHINGELSE,
ApiError::STATUS_OK
);
if (in_array($status, $valid_statuses)) {
// it's an acceptable value
}
To whitelist all constants of a class, you could use reflection and retrieve the constants from ApiError
via ReflectionClass::getconstants()
$refl = new ReflectionClass('ApiError');
$valid_statuses = $refl->constants();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With