0

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();
    }
}
8
  • "The above code throws an error" Some secret error, I presume? Commented May 11, 2023 at 11:20
  • @u_mulder: for this case "Warning: Undefined variable $Meow\Meow::BAR" Commented May 11, 2023 at 11:22
  • Please add all relevant information to the question body. Commented May 11, 2023 at 11:23
  • constant(self::class . "::" . $constant) Commented May 11, 2023 at 11:23
  • @u_mulder: You won! Did not know there is a function like that, thank you <3 Commented May 11, 2023 at 11:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.