引用 PHP 中的静态方法? [英] Reference to static method in PHP?

查看:27
本文介绍了引用 PHP 中的静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

( 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();

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

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

推荐答案

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

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

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

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

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

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

<?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();

这篇关于引用 PHP 中的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆