Reputation: 1229
I mean, I have a string: "class cl{...}"
, and I would like to include it. I know there is the eval
function, but is it the best way to do it?
Upvotes: 0
Views: 98
Reputation: 157890
This is some sort of custom for PHP users to ask this kind of questions: to devise some unusual and unreliable mechanism, then get stuck with it and then come to Stack Overflow with a question. And we have a typical XY problem with a smell of insecurity. And a smelly answer as well, as SO is strictly direct in it's answers.
Why you have to have it upside down: come with a question first, and then get the proper solution for your real problem.
Upvotes: 1
Reputation: 312
Ok can use call_user_func to dynamically call object
namespace Foobar;
class Foo {
static public function test() {
print "Hello world!\n";
}
}
call_user_func(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0
call_user_func(array(__NAMESPACE__ .'\Foo', 'test')); // As of PHP 5.3.0
In your case :
$obj = '\Foo';
$method = 'test';
call_user_func(array(__NAMESPACE__ .$obj, $method));
Upvotes: 1
Reputation: 3537
It depends why you have this as a string. Where does it come from?
If it is user generated, i.e. a user input, better not put it through eval. The user could easily run any code on your website!
If you read this from a file and know it is legitimate, just use include
on that file. But you also could use eval
. It is just important that that string is not user generated!
Upvotes: 2