问题描述
有关PHP中语法/语法功能的问题。例如,在声明对象时使用变量存储类名称:
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.
推荐答案
您无法在PHP中使用明智的表达式来做到这一点,例如。
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.
这篇关于使用常量声明PHP中的对象以保存类名(就像可以使用变量一样)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!