引用 PHP 中的静态方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/192111/
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-24 21:53:08  来源:igfitidea点击:

Reference to static method in PHP?

phpsyntax

提问by Eric

In PHP, I am able to use a normal function as a variable without problem, but I haven't figured out how to use a static method. Am I just missing the right syntax, or is this not possible?

在 PHP 中,我可以毫无问题地使用普通函数作为变量,但我还没有弄清楚如何使用静态方法。我只是缺少正确的语法,还是不可能?

(EDIT: the first suggested answer does not seem to work. I've extended my example to show the errors returned.)

(编辑:第一个建议的答案似乎不起作用。我扩展了我的示例以显示返回的错误。)

function foo1($a,$b) { return $a/$b; }

class Bar
{
    static function foo2($a,$b) { return $a/$b; }

    public function UseReferences()
    {
        // WORKS FINE:
        $fn = foo1;
        print $fn(1,1);

        // WORKS FINE:
        print self::foo2(2,1);
        print Bar::foo2(3,1);

        // DOES NOT WORK ... error: Undefined class constant 'foo2'
        //$fn = self::foo2;
        //print $fn(4,1);

        // DOES NOT WORK ... error: Call to undefined function self::foo2()
        //$fn = 'self::foo2';
        //print $fn(5,1);

        // DOES NOT WORK ... error: Call to undefined function Bar::foo2()        
        //$fn = 'Bar::foo2';
        //print $fn(5,1);

     }
}

$x = new Bar();
$x->UseReferences();

(I am using PHP v5.2.6 -- does the answer change depending on version too?)

(我使用的是 PHP v5.2.6 - 答案是否也会因版本而异?)

回答by Peter Bailey

PHP handles callbacks as strings, not function pointers. The reason your first test works is because the PHP interpreter assumes foo1as a string. If you have E_NOTICE level error enabled, you should see proof of that.

PHP 将回调作为字符串处理,而不是函数指针。您的第一个测试有效的原因是 PHP 解释器将foo1假定为字符串。如果您启用了 E_NOTICE 级别错误,您应该会看到证明。

"Use of undefined constant foo1 - assumed 'foo1'"

“使用未定义的常量 foo1 - 假定为 'foo1'”

You can't call static methods this way, unfortunately. The scope (class) is relevant so you need to use call_user_func instead.

不幸的是,您不能以这种方式调用静态方法。范围(类)是相关的,因此您需要改用 call_user_func。

<?php

function foo1($a,$b) { return $a/$b; }

class Bar
{
    public static function foo2($a,$b) { return $a/$b; }

    public function UseReferences()
    {
        $fn = 'foo1';
        echo $fn(6,3);

        $fn = array( 'self', 'foo2' );
        print call_user_func( $fn, 6, 2 );
     }
}

$b = new Bar;
$b->UseReferences();

回答by rewbs

In php 5.2, you can use a variable as the method name in a static call, but to use a variable as the class name, you'll have to use callbacks as described by BaileyP.

在 php 5.2 中,您可以在静态调用中使用变量作为方法名,但要使用变量作为类名,您必须使用 BaileyP 描述的回调。

However, from php 5.3, you canuse a variable as the class name in a static call. So:

但是,从 php 5.3 开始,您可以在静态调用中使用变量作为类名。所以:

class Bar
{
    public static function foo2($a,$b) { return $a/$b; }

    public function UseReferences()
    {
        $method = 'foo2';
        print Bar::$method(6,2); // works in php 5.2.6

        $class = 'Bar';
        print $class::$method(6,2); // works in php 5.3
     }
}

$b = new Bar;
$b->UseReferences();
?>

回答by Jiangge Zhang

You could use the full name of static method, including the namespace.

您可以使用静态方法的全名,包括命名空间。

<?php
    function foo($method)
    {
        return $method('argument');
    }

    foo('YourClass::staticMethod');
    foo('Namespace\YourClass::staticMethod');

The name array array('YourClass', 'staticMethod')is equal to it. But I think the string may be more clear for reading.

name 数组array('YourClass', 'staticMethod')等于它。但我认为字符串可能更易于阅读。

回答by dwallace

In PHP 5.3.0, you could also do the following:

在 PHP 5.3.0 中,您还可以执行以下操作:

<?php

class Foo {
    static function Bar($a, $b) {
        if ($a == $b)
            return 0;

        return ($a < $b) ? -1 : 1;
    }
    function RBar($a, $b) {
        if ($a == $b)
            return 0;

        return ($a < $b) ? 1 : -1;
    }
}

$vals = array(3,2,6,4,1);
$cmpFunc = array('Foo', 'Bar');
usort($vals, $cmpFunc);

// This would also work:
$fooInstance = new Foo();
$cmpFunc = array('fooInstance', 'RBar');
// Or
// $cmpFunc = array('fooInstance', 'Bar');
usort($vals, $cmpFunc);

?>

回答by hek2mgl

In addition to what was said you can also use PHP's reflection capabilities:

除了上面所说的,您还可以使用 PHP 的反射功能:

class Bar {

    public static function foo($foo, $bar) {
        return $foo . ' ' . $bar;
    }


    public function useReferences () {
        $method = new ReflectionMethod($this, 'foo');
        // Note NULL as the first argument for a static call
        $result = $method->invoke(NULL, '123', 'xyz');
    }

}

回答by Camilo Martin

Coming from a javascript background and being spoiled by it, I just coded this:

来自 javascript 背景并被它宠坏了,我只是这样编码:

function staticFunctionReference($name)
{
    return function() use ($name)
    {
        $className = strstr($name, '::', true);
        if (class_exists(__NAMESPACE__."\$className")) $name = __NAMESPACE__."\$name";
        return call_user_func_array($name, func_get_args());
    };
}

To use it:

要使用它:

$foo = staticFunctionReference('Foo::bar');
$foo('some', 'parameters');

It's a function that returns a function that calls the function you wanted to call. Sounds fancy but as you can see in practice it's piece of cake.

它是一个函数,它返回一个调用您想要调用的函数的函数。听起来很花哨,但正如您在实践中看到的那样,这是小菜一碟。

Works with namespaces and the returned function should work just like the static method - parameters work the same.

使用命名空间和返回的函数应该像静态方法一样工作 - 参数工作相同。

回答by Camilo Martin

This seems to work for me:

这似乎对我有用:

<?php

class Foo{
    static function Calc($x,$y){
        return $x + $y;
    }

    public function Test(){
        $z = self::Calc(3,4);

        echo("z = ".$z);
    }
}

$foo = new Foo();
$foo->Test();

?>

回答by Joe

"A member or method declared with static can not be accessed with a variable that is an instance of the object and cannot be re-defined in an extending class"

“用静态声明的成员或方法不能用作为对象实例的变量访问,不能在扩展类中重新定义”

(http://theserverpages.com/php/manual/en/language.oop5.static.php)

( http://theserverpages.com/php/manual/en/language.oop5.static.php)