【问题标题】:Use variable's string into class names or other将变量的字符串用于类名或其他
【发布时间】:2013-07-16 05:00:45
【问题描述】:

我想在类名中使用变量。

例如,让我们将一个名为$var 的变量设置为“index2”。 现在我想在这样的类名中打印index2

controller_index2,但不是手动执行,我可以像这样打印 var 名称:

controller_$var;

但我认为这是语法错误。

我该怎么做?

    function __construct()
    {
        $this->_section = self::path();

        new Controller_{$this->_section};

    }

【问题讨论】:

  • 你不能用变量名声明一个类。

标签: php class-names


【解决方案1】:

你可以这样做....遵循这个语法

function __construct()
{
    $this->_section = self::path();
    $classname = "Controller_".$this->_section;
    $instance = new $classname();

}

从字符串定义创建对象的另一种方法是使用ReflectionClass

$classname = "Controller_".$this->_section;
$reflector = new ReflectionClass($classname);

如果你的类名没有构造函数参数

$obj = $reflector->newInstance();

如果你需要将参数传递给构造函数,你可以使用任何一个

$obj = $reflector->newInstance($arg1, $arg2);

或者如果你有你的参数在一个数组中

$obj = $reflector->newInstanceArgs($argArray);

【讨论】:

    【解决方案2】:

    只是为了补充前面的答案,如果您尝试使用变量名声明新类但所有构造参数都相同并且您正在处理实例对象都一样,那么您可能不需要不同的类,而只是相同的不同实例。

    【讨论】:

      【解决方案3】:

      这是一个可怕的 hack,但是:

      php > class foo { function x_1() { echo 'success'; } };
      php > $x = new foo;
      php > $one = 1;
      php > $x->{"x_$one"}();
                ^^^^^^^^^^^^
      success
      

      与其尝试将方法名称即时构建为字符串,不如使用方法数组更合适。然后你只需使用你的变量作为数组的键。

      【讨论】:

        【解决方案4】:

        试试这个:

          $name = "controller_$var";
          echo $this->$name;
        

        【讨论】:

          【解决方案5】:

          将其作为双引号中的字符串回显。

          echo "controller_{$var}";
          

          试试这个(根据您在 OP 中的代码):

          function __construct()
          {
              $this->_section = self::path();
          
              $controller_name = "Controller_{$this->_section}";
          
              $controller = new $controller_name;
          
          }
          

          【讨论】:

          • 没问题@JunatanmDegraded :-D
          • 我现在收到一个错误解析错误:语法错误,第 28 行 C:\xampp\htdocs\framework\includes\class\Core.class.php 中的意外 '{'
          猜你喜欢
          • 1970-01-01
          • 2016-01-06
          • 2011-10-31
          • 2019-12-17
          • 2014-10-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多