I have a php class Assets. Within Assets there are a variety of public functions which handle assets (caching, minifying, combining…). One of the public functions contains a secondary function which is required to perform a preg_replace_callback(). This inner function needs to access one of the other public functions but I am having trouble calling the other functions.
Here is the setup:
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
);
. . .
}
}
Here’s what I have tried:
$this->img($matched)Error: Using $this when not in object context – Refers to
$this->
inside ofparseCSS()
Assets::img($matched)Error: Using $this when not in object context – Refers to
$this->
inside ofimg()
So, how can I access a public function with $this from within an inner function?
This would be more appropriate:
Your original approach causes
parseCSSto be defined every timecssis called — which will probably result in a fatal error were you to ever callcsstwice. All questions of scope are also much more straightforward in my revised example. In your original example,parseCSSis a function in the global scope, and not associated with your class.Edit: Valid callback formulations are documented here: http://php.net/manual/en/language.types.callable.php
A closure-based solution is also possible as of PHP 5.4 — this would actually be similar to what you originally intended.