类中的php回调函数 [英] php callback function in class

查看:201
本文介绍了类中的php回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些原因,我们的托管公司使用了PHP 5.2,甚至没有预先安装mysqli和PDO.

for some reasons, our hosting company used PHP 5.2 and doesn't even have mysqli and PDO pre-installed.

我别无选择,只能重写部分代码以使其与5.2兼容.

I have no choice but to rewrite some part of my code to make it 5.2 compatible.

所以,这是我的问题:

在PHP 5.2中,不支持匿名函数,因此我进行了以下测试以确保我正确地更改了代码:

In PHP 5.2 Anonymous function is not supported, so i did the following test to make sure I'm changing the code correctly:

class foo{

    public function toString(){
        $arr = array("a", "b");
        $arr2 = array("c", "d");
        print_r(array_map('mapKeyValue', $arr, $arr2));
    }

    private function mapKeyValue($v, $k){
        return $k."='".$v."'";
    }
}

$foo = new foo();
echo $foo->toString();

但是以上内容会给我:

Warning: array_map() expects parameter 1 to be a valid callback, function 'mapKeyValue' not found or invalid function name in ....
PHP Warning: array_map() expects parameter 1 to be a valid callback, function 'mapKeyValue' not found or invalid function name in ....

正确的方法是:

array_map('mapKeyValue', $arr, $arr2);

在课堂上?

PS:是否因为使用PHP 5.2而更改托管公司是一个足够好的理由?(我还剩下大约7个月的合同)

PS: Is it a good enough reason to change hosting company because they use PHP 5.2?(i got a contract with about 7 month left)

推荐答案

使用$this和一个数组作为回调:

Use $this and an array as the callback:

array_map( array( $this, 'mapKeyValue'), $arr, $arr2);

而且,可以肯定的是,这已经经过PHP 5.2.17的测试,并且可以正常工作.

And, just to be sure, this is tested with PHP 5.2.17 and is confirmed working.

这篇关于类中的php回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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