Initiating a class from string with extra step?

后端 未结 2 1908
梦毁少年i
梦毁少年i 2021-01-23 19:01

I\'ve been looking into substantiating a new class instance from a string in PHP. This is seems to be an acceptable procedure, however I am curious why it can\'t be done with th

2条回答
  •  天涯浪人
    2021-01-23 19:42

    There are exactly four options of creating a class instance using new that I know:

    • Name class directly: $bar = new Bar;
    • Use variable directly: $barName = 'Bar'; $bar = new $barName;
    • Use object property: $obj = (object) ['barName' => 'Bar']; $bar = new $obj->barName;
    • Use existing instance: $bar1 = new Bar; $bar2 = new $bar1;

    First half of an answer to your question is PHP parser: it prohibits many things like new (Foo) and new "Foo" that could used to build a hack.

    Second half may hide in PHP sources: here's the C function that throws that exception.

提交回复
热议问题