eval in outside object use inside other object context

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
koen.h
Forum Contributor
Posts: 268
Joined: Sat May 03, 2008 8:43 am

eval in outside object use inside other object context

Post by koen.h »

Title says it all :mrgreen:

Use case:
Piece of code in the db. Using a class to get it and eval() it. Problem is that the context wherein the code is eval'd is not the context I won't. The context that should be the scope of the eval'd code is the place that calls the code that extracts the code out of the db.

Eg:

Code: Select all

 
class A {
    private $loader;
 
    public function setLoader(ILoader $loader) {
        $this->loader = $loader;
    }
 
    public function specialFunction() {
        $this->loader->load('somename'); // should have same effect as require_once('somename');
    }
}
 
class DbLoader implements ILoader {
    public function load($file) {
        // extract code out of DB and eval it;
    }
}
 
class RequireLoader implements ILoader {
    public function load($file) {
        // require = file_get_contents + eval
    }
}
 
interface ILoader {
    public function load($file);
}
 
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: eval in outside object use inside other object context

Post by VladSun »

What about using http://bg2.php.net/create_function to create your "specialFunction()"?

Do you mean that you want to access $this context?
There are 10 types of people in this world, those who understand binary and those who don't
koen.h
Forum Contributor
Posts: 268
Joined: Sat May 03, 2008 8:43 am

Re: eval in outside object use inside other object context

Post by koen.h »

VladSun wrote:What about using http://bg2.php.net/create_function to create your "specialFunction()"?

Do you mean that you want to access $this context?
Yes, the "inluded" code refers to $this so an object scope must be active.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: eval in outside object use inside other object context

Post by VladSun »

A workaround:

Code: Select all

class A
{
    public $var = 'ok';
    
    public function __call($name, $arguments)
    {
        //$s = get_from_db($name)   
        
        // Trial code
        $code = 'echo "'.$name.'::".$obj->var;';
        
        $lf = create_function('&$obj', $code);
        $lf($this);
    } 
}
 
$inst = new A();
 
$inst->func1();
And you should use $obj instead of $this in your DB stored code.
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply