PHP:调用没有类名的静态方法
I have simllar question like here: static-method-invocation, but in PHP. Simply, I want have class like this:
static class ClassName{ static public function methodName(){ //blah blah blah } }
and I want to call member method without name od class like this:
require_once(ClassName.php); methodName();
Is it possible in PHP? Thanks for your answers!
我有类似的问题: static-method-invocation ,但在PHP中。 简单地说,我想要这样的类: p>
static class ClassName { static public function methodName(){ // blah blah blah } } code> pre> blockquote>
我想调用没有名称od类的成员方法,如下所示: p>
require_once(ClassName.php); methodName(); code> pre> blockquote>
是否可能 用PHP? 谢谢你的回答! p> div>
You can not do what you're looking for. The example call you give:
methodName();
Is calling a global function. Even static class functions are global as well, they always need the class-name to be called:
ClassName::methodName();
This calls the global static class function you've created in the include file.
I can only guess what you'd like to achieve, maybe you can benefit from the feature that includes can return values:
static class ClassName{
static public function methodName(){
//blah blah blah
}
}
return 'ClassName';
Including:
$className = require_once(ClassName.php);
$className::methodName();
However this won't work with reguire_once
when the file has been loaded earlier.
You can write a wrapper function to require_once
files, store their return value into a global context array that keeps these values based on the file-name of the include.
Keep in mind that the java language differs from PHP. The equivalent to the java static function would be the global function in PHP:
function methodName(){
//blah blah blah
}
Including:
require_once(ClassName.php);
methodName();
That's the PHP equivalent.
only way
$ClassName = 'MyClass';
require_once($ClassName.'.php');
$ClassName::methodName();