Defining a trait I want to write a method which gets the content of a class constant if it exists and is an array, return an empty error otherwise. Just not easy to figure out how to evaluate this class constant call as PHP code.
trait FooBar {
public static function getChildArrayConstant(string $constant): array
{
$result = defined(self::class . "::" . $constant) ? ${self::class . "::" . $constant} : [];
return is_array($result) ? $result : [];
}
public function do() {
var_dump(self::getChildArrayConstant("FOO"); // shall return []
var_dump(self::getChildArrayConstant("BAR"); // shall return ["foo","bar"]
}
}
The above code throws an error. I tried various things including eval()
, errors always. How would I simple evaluate that correctly to give me the value of the class constant if it exists?
Example of implementing class:
class Meow {
use FooBar;
public const BAR = ["foo", "bar"];
public function doMeow() {
$this->do();
}
}