PHP: constant as a variable in a function

I am trying to use a constant as a function parameter, is it possible to check the type of this constant.

An example of what I want:

class ApiError { const INVALID_REQUEST = 200; } class Response { public function status(ApiError $status) { //function code here } } 

Using:

 $response = new Response(); $response->status(ApiError::INVALID_REQUEST); 

This shoud checks that the given $ status is a constant of the ApiError class. Is this possible?

+6
source share
5 answers

As already mentioned, there is no universal solution. But if you want to do this very simply, model each “object” you are dealing with (= every possible status), for example:

 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 gives you many classes because you encapsulate primes, but also with the ability to type input.

+10
source

You can use in_array() to check for white values, which is the recommended strategy when you need to check input for a specific set of values:

 // 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 an acceptable value } 

To list all class constants, you can use reflection and get constants from ApiError via ReflectionClass::getconstants()

 $refl = new ReflectionClass('ApiError'); $valid_statuses = $refl->constants(); 
+5
source

Another approach is to change the call. If we want to check if a constant exists, this line will be too late. $response->status(ApiError::INVALID_REQUEST);

The php interpreter also checks for the existence of a constant and will die with Fatal Error. This is not fun with try ().

Therefore, I would suggest using a string as a parameter to check for existence using certain () and constants ()

 class ApiError { const INVALID_REQUEST = 200; } class Response { public function status($status) { if (!defined('ApiError::'.$status)) { return false; // Or throw Exception / other error handling } $errorCode = constant('ApiError::'.$status); //function code here return true; } } 

Then use will look like this:

 $response = new Response(); $response->status('INVALID_REQUEST'); 

The bad news is that there are no type hints for this solution.

+2
source

I like this approach best:

 class NoticeType { const INFO = 'neutral'; const WARN = 'alert'; const FAIL = 'critical'; const PASS = 'success'; const LITE = 'brand'; private $_type; function __construct($NOTICE_constant) { if (!preg_match('/neutral|alert|critical|success|brand/', $NOTICE_constant)) throw new \Exception('Invalid parameter for '.__CLASS__.' constructor'); $this->_type = $NOTICE_constant; } function getType() { return $this->_type; } function __toString() { return $this->_type; } static function INFO () { return new NoticeType(self::INFO); } static function WARN () { return new NoticeType(self::WARN); } static function FAIL () { return new NoticeType(self::FAIL); } static function PASS () { return new NoticeType(self::PASS); } static function LITE () { return new NoticeType(self::LITE); } } 

Usage is very straight forward and you have to go astray:

 function test (NoticeType $n) { echo ($n == NoticeType::INFO)."\n"; } test (NoticeType::INFO()); 
0
source

SplEnum can help. An example from PHP docs:

 class Month extends SplEnum { const __default = self::January; const January = 1; const February = 2; const March = 3; const April = 4; const May = 5; const June = 6; const July = 7; const August = 8; const September = 9; const October = 10; const November = 11; const December = 12; } echo new Month(Month::June) . PHP_EOL; try { new Month(13); } catch (UnexpectedValueException $uve) { echo $uve->getMessage() . PHP_EOL; } 

Exit:

 6 Value not a const in enum Month 
0
source

Source: https://habr.com/ru/post/918303/


All Articles