Alex Rivera | Logout

PHP: constant as variable in function

Asked 2012-06-17T21:09:39.390
8

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?

Edit
Report

1 Answer

5

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();
answered 2012-06-17T21:11:57.633

Your Answer