php 如果我只有一个类名字符串,如何从类中调用静态方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/997968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:35:45  来源:igfitidea点击:

How can I call a static method from a class if all I have is a string of the class name?

php

提问by James Skidmore

How would I get something like this to work?

我怎样才能得到这样的工作?

$class_name = 'ClassPeer';
$class_name::doSomething();

回答by jimyi

Depending on version of PHP:

取决于 PHP 的版本:

call_user_func(array($class_name, 'doSomething'));
call_user_func($class_name .'::doSomething'); // >5.2.3

回答by David Garcia

To unleash the power of IDE autocomplete and error detection, use this:

要释放 IDE 自动完成和错误检测的强大功能,请使用以下命令:

$class_name = 'ClassPeer';

$r = new \ReflectionClass($class_name );

// @param ClassPeer $instance

$instance =  $r->newInstanceWithoutConstructor();

//$class_name->doSomething();
$instance->doSomething();

Basically here we are calling the static method on an instance of the class.

基本上,我们在这里调用类的实例上的静态方法。

回答by TJ L

Use call_user_func. Also read up on PHP callbacks.

使用call_user_func. 还阅读了 PHP callbacks

call_user_func(array($class_name, 'doSomething'), $arguments);

回答by apandit

Reflection (PHP 5 supports it) is how you'd do this. Read that page and you should be able to figure out how to invoke the function like that.

反射(PHP 5 支持它)是您执行此操作的方式。阅读该页面,您应该能够弄清楚如何调用这样的函数。

$func = new ReflectionFunction('somefunction');
$func->invoke();

Documentation Link

文档链接

回答by MaxZoom

After I have almost missed the simplest solution from VolkerK, I have decided to extend and put it in a post. This is how to call the static members on the instance class

在我几乎错过了来自 VolkerK 的最简单的解决方案之后,我决定将其扩展并放在一个帖子中。这是如何调用实例类上的静态成员

// calling class static method
$className = get_class($this);
$result = $className::caluclate($arg1, $arg2);

// using class static member
foreach ($className::$fields as $field) {
  :
}