Vic*_*ilo 1 php scope function
我有一个php类Assets.在内部Assets有各种处理资产的公共功能(缓存,缩小,组合......).其中一个公共函数包含执行a所需的辅助函数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
);
. . .
}
}
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的:
$this->img($matched)错误:不在对象上下文中时使用$ this - 引用
$this->内部parseCSS()
Assets::img($matched)错误:不在对象上下文中时使用$ this - 引用
$this->内部img()
那么,如何$this从内部函数中访问公共函数?
这样更合适:
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()
}
Run Code Online (Sandbox Code Playgroud)
您的原始方法会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);
Run Code Online (Sandbox Code Playgroud)
一个封闭为基础的解决方案,也可以作为PHP 5.4的-这实际上是类似于您最初的预期.