By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,408 Members | 1,624 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,408 IT Pros & Developers. It's quick & easy.

why can't you use eval() to create a class definition?

P: n/a

We are probably lucky that PHP doesn't allow this, but I'm curious
about what the argument is against allowing this? Why did the inventors
of PHP keep this from working? This same thing, using eval to create a
class defintion, works in Javascript, demonstrating, perhaps, that
Javascript is very flexible and you can do awful things with it.

Anyway, the following code prints out "class does not exist".
<?php

// 05-26-05 - just a personal demo to satify my personal curiosity to
see if eval() will
// create a class definition

$string = "class SendFormattedText { ";
$string = "function boldText() { ";
$string = " echo \"<b>The world is a good place</b>\" ";
$string = " } } ";

eval($string);

if (class_exists("SendFormattedText")) {
$obj = new SendFormattedText();
$obj->boldText();
} else {
echo "<p>class does not exist ";
}

?>

Jul 17 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
lk******@geocities.com wrote:
We are probably lucky that PHP doesn't allow this, but I'm curious
about what the argument is against allowing this? Why did the
inventors of PHP keep this from working? This same thing, using eval
to create a class defintion, works in Javascript, demonstrating,
perhaps, that Javascript is very flexible and you can do awful things
with it.

Anyway, the following code prints out "class does not exist".


Not when you use valid code:

$string = "class SendFormattedText { ";
$string .= "function boldText() { ";
$string .= " echo \"<b>The world is a good place</b>\";";
$string .= "}}";

eval($string);
But, do yourself a favor and forget that eval exists...
JW

Jul 17 '05 #2

P: n/a
Thanks for that, I missed the semi-colon.

But, do yourself a favor and forget that eval exists...


But I don't know how to get a template to render PHP commands without
eval(). I get a template from a database as a string and it has PHP
commands in it. How can I get it to work without eval()?

Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.