【问题标题】:php object variable as classnamephp 对象变量作为类名
【发布时间】:2014-05-16 17:24:50
【问题描述】:

当我想使用变量静态访问 JSON 类时,这是可能的。

代码:

<?php
$classname = "JSON";
$classname::echo_output();
?>

但是当我想使用一个对象变量来静态访问该类时,它会失败。 代码:

<?php
class someclass{
public $classname = "JSON";
    public function __construct(){
        $this->classname::echo_output();
    }
}
?>

自己试试吧。

我的解决方法是 $classname = $this->classname; 但是有没有其他可能的方法来解决这个问题?

【问题讨论】:

  • “echo_output()”函数定义在哪里?
  • 从外观上看,您使用的是自定义 JSON 类,并且已经解决了您遇到的问题。您还有其他问题吗?

标签: php class static


【解决方案1】:

你可以使用call_user_func函数来实现这个

<?php

class someclass{

public $classname = "JSON";

    public function __construct(){
        call_user_func([$this->classname, 'echo_output']);
    }

}
?>

【讨论】:

  • 这样我不能加参数可以吗?
  • @Ismail 你实际上可以添加参数,只要这样调用它: call_user_func(['JSON', 'echo_output'], $param1, $param2, ... , $paramN);从手册中查找。
【解决方案2】:

如果 echo_output 确实存在于您调用的类中,这应该可以工作,但您必须先将该属性分配给一个变量。

public function __construct(){
    $classname = $this->classname;
    $classname::echo_output();
}

【讨论】:

【解决方案3】:

通过 PHP 5.4+,您可以在一行中使用 ReflectionClass 完成此操作。

(new \ReflectionClass($this->classname))->getMethod('echo_output')->invoke(null);

PHP 5.4 下

call_user_func(array($this->classname, 'echo_output'));

但我不建议这样做。

您应该创建实例、注入它们并调用它们的方法,而不是使用静态方法...

interface Helper{
    public function echo_output();
}

class JSONHelper implements Helper {
    ...
}

class someclass{
    public function __construct(Helper $helper){
        $helper->echo_output();
    }
}

new someclass(new JSONHelper()); //multiple instances
new someclass(JSONHelper::getInstance()); //singleton
new someclass($helperFactory->createHelper()); //factory
new someclass($container->getHelper()); //IoC container

【讨论】:

    【解决方案4】:

    根据一些研究和 javascript 知识,此解决方案将是最简单的。

    <?php
    class someclass{
    public $classname = "JSON";
        public function __construct(){
            $that = (array) $this;
            $that["classname"]::echo_output();
        }
    }
    ?>
    

    只需将对象转换为数组。

    这样您就不必为每个动态类名定义一个变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-06
      • 2010-11-25
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多