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

℡╲_俬逩灬. 提交于 2020-01-30 10:38:09

问题


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

$className= 'myClass';
$obj = new $className;

I was wondering if there were some way to do the same with constants. Something along the lines of:

define('CLASS_NAME','myClass');
$obj = new {CLASS_NAME};

This doesn't work. Obviously I could just use a variable as an intermediary step, but I was mostly just wondering for edification purposes whether this was a formatting issue or if this is just not possible to do directly in this way.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/42735428/declare-an-object-in-php-using-constant-to-hold-class-name-like-you-can-do-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!