如何在类{function {function}}中引用$ this?

时间:2012-10-24 18:09:17

标签: php function scope

我有一个php类Assets。在Assets内,有各种处理资产的公共函数(缓存,缩小,组合......)。其中一个公共函数包含执行preg_replace_callback()所需的辅助函数。这个内部函数需要访问其他一个公共函数,但是我无法调用其他函数。

以下是设置:

class Assets
{

    public function img($file)
    {

        $image['location'] = $this->image_dir.$file;
        $image['content'] = file_get_contents($image['location']);
        $image['hash'] = md5($image['content']);
        $image['fileInfo'] = pathinfo($image['location']);

        return $this->cache('img',$image);

    }

    public function css($content)
    {

        . . .

        function parseCSS($matched){

            return $this->img($matched); // THIS LINE NEEDS TO REFERENCE function img()

        }

        $mend = preg_replace_callback(
            '#\<parse\>(.+?)\<\/parse\>#i',
            'parseCSS',
            $this->combined_css
        );

        . . .

    }

}

以下是我的尝试:

  

$this->img($matched)

     

错误:不在对象上下文中时使用$ this - 引用$this->   在parseCSS()

内      

Assets::img($matched)

     

错误:不在对象上下文中时使用$ this - 引用$this->   在img()

那么,如何从内部函数中使用$this访问公共函数?

2 个答案:

答案 0 :(得分:5)

这更合适:

public function css($content)
{
    //. . .
    $mend = preg_replace_callback(
        '#\<parse\>(.+?)\<\/parse\>#i',
        array($this, 'parseCSS'),
        $this->combined_css
    );
    //. . .
}

public function parseCSS($matched){
    return $this->img($matched); // THIS LINE NEEDS TO REFERENCE function img()
}

您的原始方法会在每次调用parseCSS时定义css - 如果您曾两次调用css,这可能会导致致命错误。在我的修订示例中,范围的所有问题都更加简单明了。在您的原始示例中,parseCSS是全局范围内的函数,与您的类无关。

编辑:此处记录了有效的回调公式:http://php.net/manual/en/language.types.callable.php

// Type 1: Simple callback
call_user_func('my_callback_function'); 

// Type 2: Static class method call
call_user_func(array('MyClass', 'myCallbackMethod')); 

// Type 3: Object method call
call_user_func(array($obj, 'myCallbackMethod'));

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// Type 5: Relative static class method call (As of PHP 5.3.0)
call_user_func(array('B', 'parent::who')); // A

//Type 6: Closure
$double = function($a) {
    return $a * 2;
};

$new_numbers = array_map($double, $numbers);

从PHP 5.4开始,基于closure的解决方案也是可行的 - 这实际上与您最初的预期类似。

答案 1 :(得分:3)

这不符合你的想法。 “内部”功能只是全局范围内的另一个功能:

<?php
class Foo
{
    public function bar()
    {
        echo 'in bar';

        function baz() {
            echo 'in baz';
        }
    }
}

$foo = new Foo();
$foo->bar();
baz();

另请注意,多次调用bar方法时会导致致命错误

<?php
class Foo
{
    public function bar()
    {
        echo 'in bar';

        function baz() {
            echo 'in baz';
        }
    }
}

$foo = new Foo();
$foo->bar();
$foo->bar();
baz();
  

致命错误:无法重新声明baz()(之前在/ code / 8k1中声明

你应该按照Frank Farmer answered的方式行事,尽管我不会使用public方法。