Is there a generally agreed upon solution in PHP for creating functions that return non-binary states? For example, if a function is going to return "success" or "failure", it's simple to just spit back a boolean but what if it needs to return failure vs. thing_1_happened vs. thing_2_happened?
In the past, I've had functions return ints or strings that match constants, like
$result = $myClass->whatever();
if ($result === MyClass::Thing1Happened) {
...
} elseif ($result === MyClass::Thing2Happened) {
...
}
But it just feels inelegant and classes end up with tons of constants only used by single functions. I imagine it's better than returning magic, unnamed values, which would lead to typo bugs (if you used strings) or reduced readability (if you used ints) but is there a better way?
If there's a correct term for "non-binary state returns" that would make this Google-able, please enlighten me.
I would recommend creating a new value object class to represent the state. The class would probably just need one member variable, state
and the possible state values could be defined with constants. Having an object like this allows you to write more complex logic against your states. This also keeps the state representation logic contained in a single class which is great for testing, preventing defects, etc.
class EventStateValueObject
{
/**
* Side note: this has to be declared as protected; if declared as public, the magic getters and setters are bypassed
* @var int
*/
protected $state;
/**
* @param string $name
* @param mixed $value
* @return void
*/
public function __set($name, $value)
{
throw new RuntimeException('Value objects are immutable');
}
/**
* @param string $name
* @return mixed
*/
public function __get($name)
{
return $this->$name;
}
/**
* @param int $state
*/
public function __construct(int $state)
{
$this->state = $state;
}
}