Declare an object in PHP using constant to hold class name (like you can do with variables)?

前端 未结 2 541
时光说笑
时光说笑 2021-01-27 16:48

This question about syntax/syntax capabilities in PHP. Take for example, using variables to store class names when declaring objects:

$className= \'myClass\';
$         


        
相关标签:
2条回答
  • 2021-01-27 17:25

    As class name (e.g. MyClass) can not be distinguished from constant name MyClass - your approach will not work.

    0 讨论(0)
  • 2021-01-27 17:26

    You can't do this with a sensible expression in PHP, as u_mulder says.

    You can do it in one line with reflection.

    $obj = (new ReflectionClass(CLASS_NAME))->newInstance();
    

    Any parameters need to go into the newInstance call.

    This is a silly idea, not least because having variable behaviour depending on class names in strings probably means bad architecture. Don't do it. But you asked if it is possible, and yes, it is.

    0 讨论(0)
提交回复
热议问题