1

I am learning PHP. I see a code including "eval" below:

<?php
$name = 'cup';
$string = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";

eval("\$cup = \"$str\";");           
echo $cup. "\n";
?>

My question is about "\$cup = \"$str\";" . Why do I have to use \, " and ; to run the above code? Simply eval($cup = $str) gives me error.

Simone Nigro
  • 4,717
  • 2
  • 37
  • 72
Asif Iqbal
  • 1,132
  • 1
  • 10
  • 23
  • _“I am learning PHP.”_ – then you best forget that `eval` exists right now. Whenever you might be tempted to use it, look real hard if there is not a better way of achieving what is needed. – CBroe Jan 25 '15 at 15:52
  • If Eval is your answer, your almost definitely asking the wrong questions. – Daryl Gill Jan 25 '15 at 16:43
  • I already have gotten my answer from Simone Nigro and it is clear to me now. Also, eval is not my answer. I was confused about parameter inside eval. Now I have known that it only holds PHP statements in the form of string. And it was my answer. – Asif Iqbal Jan 25 '15 at 17:24

1 Answers1

1

Simply eval($cup = $str) is wrog, eval need a string, eg;

eval('$cup = $str;'); // this work

now, if use double quote, eg

eval("\$cup = \"$str\";");     

in double quote strings variables in the strings will be evaluated. eg:

$cup = 'hello';
$str = 'world';
eval("$cup = \"$str\";"); // eval("hello = \"world\";");   

\is a escape characters

$cup = 'hello';
$str = 'world';
eval("\$cup = \"$str\";"); // eval("$cup = \"world\";"); 

recommended reading: PHP Strings

Side note: PHP eval is evil (use very, very careful)

Community
  • 1
  • 1
Simone Nigro
  • 4,717
  • 2
  • 37
  • 72