如何在匿名函数中检索类的方法?

时间:2013-07-05 09:34:23

标签: php

如何在匿名函数中检索类的方法?还有其他机会来解决这个问题吗?

任务: 我需要从远程路径上传图像并将其更改为本地路径。

代码:

    $pattern = '/<img src=(.*?jpg|gif|png).*?>/m';

    $uploadImage = function($image)
    {
        $this->uploadPictures();
    };

    function image_replace($matches) use ($uploadImage)
    {
        // как обычно: $matches[0] -  полное вхождение шаблона
        // $matches[1] - вхождение первой подмаски,
        // заключенной в круглые скобки, и так далее...
        $uploadImage($matches[1]);

        return $matches[1].($matches[2]+1);
    }

    preg_replace_callback(
        $pattern,
        "image_replace",
        $text);

3 个答案:

答案 0 :(得分:1)

$pattern = '/<img src=(.*?jpg|gif|png).*?>/m';

$uploadImage = function ($image) {
    $this->uploadPictures();
};

$image_replace = function ($matches) use ($uploadImage) {
    $uploadImage($matches[1]);
    return $matches[1].($matches[2]+1);
};

preg_replace_callback($pattern, $image_replace, $text);

$pattern = '/<img src=(.*?jpg|gif|png).*?>/m';

$image_replace = function ($matches) {
    $this->uploadPictures($matches[1]);
    return $matches[1].($matches[2]+1);
};

preg_replace_callback($pattern, $image_replace, $text);

$pattern = '/<img src=(.*?jpg|gif|png).*?>/m';

preg_replace_callback($pattern, function ($matches) {
    $this->uploadPictures($matches[1]);
    return $matches[1].($matches[2]+1);
}, $text);

答案 1 :(得分:0)

您可以将类对象传递给匿名函数

$uploadImage = function($image, $this)
{
    $this->uploadPictures();
};

答案 2 :(得分:0)

从PHP 5.4 $this可用于匿名函数(请参阅changelog here)。

因此,代码如下:

<?php
class A
{
    public function test()
    {
        $f = function()
        {
            return $this->callback();
        };
        return $f();
    }

    public function callback()
    {
        return 'test';
    }
}

$a = new A();
echo $a->test();

完全有效,从5.4开始。

在PHP 5.3中,您可以使用use运算符实现相同的功能:

public function test()
{
    $_this = &$this;
    $f = function() use (&$_this)
    {
        return $_this->callback();
    };
    return $f();
}

在PHP 5.3之前,您可以避免通过使用函数参数来使用use关键字:

public function test()
{
    $f = function($_this)
    {
        return $_this->callback();
    };
    return $f($this);
}

最后,当谈到静态方法时,您还可以使用__CLASS__常量。

public function test()
{
    $f = function()
    {
        return call_user_func(array(__CLASS__, 'callback'));
    };
    return $f();
}

......虽然它很难看。

相关问题