如何通过eval运行代码


How to run code through eval?

这是我的循环代码

<?php
for ($x=0; $x<=10; $x++)
  {
  echo "The number is: $x <br>";
  }
?> 

我想用eval运行这段代码,那么我该怎么运行呢。我试过这个

<?php
$var = ("for ($x=0; $x<=10; $x++)
  {
  echo 'The number is: $x <br>';
  }");
  eval($var);
?> 

我想运行这段代码来学习eval函数。我正在尝试,但没有得到任何答案。请把你的答案告诉我。请帮我做这个。

尝试将双引号改为单引号。默认情况下,双引号读取变量的值,因此您实际编写的内容(假设未设置$x)不是for ($x=0; $x<=10; $x++),而是for (=0; <=10; ++),这将不起作用。

它不起作用,因为在双引号字符串中,变量仍在求值。您的代码应该使用简单的引号才能工作:

<?php
$var = 'for ($x=0; $x<=10; $x++)
  {
  echo "The number is: $x <br>";
  }';
  eval($var);
?> 

请注意,对于要由echo求值的变量$x,内部字符串仍应使用双引号。

问题是使用了双引号。当双引号字符串经过评估阶段时,$x变量将被解释,这与原始echo中的情况非常相似。

如果你把它改为使用单引号,它应该可以工作:

<?php
$var = ('for ($x=0; $x<=10; $x++)
  {
  echo ''The number is: ''.$x.'' <br>'';
  }');
  eval($var);
?>

哪个是的评估版本

<?php
 for ($x=0; $x<=10; $x++)
   {
   echo 'The number is: '.$x.' <br>';
   }
?>

在我的控制台上打印:

C:'SO>php -v
PHP 5.3.2 (cli) (built: Mar  3 2010 20:47:01)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
    with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans
C:'SO>php test.php
The number is: 0 <br>The number is: 1 <br>The number is: 2 <br>The number is: 3
<br>The number is: 4 <br>The number is: 5 <br>The number is: 6 <br>The number is
: 7 <br>The number is: 8 <br>The number is: 9 <br>The number is: 10 <br>
C:'SO>