php对象变量作为类名
当我想使用变量静态访问类JSON时,这是可能的 代码:php对象变量作为类名,php,class,static,Php,Class,Static,当我想使用变量静态访问类JSON时,这是可能的 代码: 但是当我想使用对象变量静态访问类时,它失败了。 代码: 你自己试试看 我如何解决它是$classname=$this->classname; 但还有其他可能的方法来解决这个问题吗?您可以使用函数来实现这一点 <?php class someclass{ public $classname = "JSON"; public function __construct(){ call_user_func
但是当我想使用对象变量静态访问类时,它失败了。
代码:
你自己试试看
我如何解决它是$classname=$this->classname;
但还有其他可能的方法来解决这个问题吗?您可以使用函数来实现这一点
<?php
class someclass{
public $classname = "JSON";
public function __construct(){
call_user_func([$this->classname, 'echo_output']);
}
}
?>
如果调用的类中确实存在echo\u输出,这应该可以工作,但必须首先将属性分配给变量
public function __construct(){
$classname = $this->classname;
$classname::echo_output();
}
通过PHP5.4+可以在一行中使用
ReflectionClass
实现这一点
(new \ReflectionClass($this->classname))->getMethod('echo_output')->invoke(null);
在PHP5.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
通过一些研究和javascript知识,这个解决方案将是最简单的
<?php
class someclass{
public $classname = "JSON";
public function __construct(){
$that = (array) $this;
$that["classname"]::echo_output();
}
}
?>
只需将对象强制转换为数组
这样,您就不必为每个动态类名定义变量。在哪里定义了“echo_output()”函数?从外观上看,您正在使用一个自定义的
JSON
类,并且已经解决了您遇到的问题。你还有其他问题吗?你是对的,我认为它会起作用,但后来又读了一遍:这样我就不能添加参数了,可以吗?@Ismail你实际上可以添加参数,就这样称呼它:call_user_func(['JSON','echo_output'],$param1,$param2,$paramN);从手册上查一下。
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
<?php
class someclass{
public $classname = "JSON";
public function __construct(){
$that = (array) $this;
$that["classname"]::echo_output();
}
}
?>