Dynamically call a static variable (array)

后端 未结 5 1220
情深已故
情深已故 2021-01-03 07:57

Here\'s my question for today. I\'m building (for fun) a simple templating engine. The basic idea is that I have a tag like this {blog:content} and I break it in a method an

5条回答
  •  星月不相逢
    2021-01-03 08:05

    You cannot do that without using eval(). $class::$template (even if it was valid syntax in PHP), would reference the static variable called $template, you would actually need variable variables ($class::$$template), which is again not valid PHP syntax (you cannot access anything from a dynamic class name in PHP, IIRC).

    I would recommend checking the variables for valid names before usng eval(), though (the regex is copied from the PHP manual):

    if (!preg_match('[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*', $class)) {
        throw new Exception('Invalid class name (' . $class . ')');
    }
    

提交回复
热议问题