如何通过eval运行代码?

时间:2013-12-05 10:50:20

标签: php

这是我的for循环代码

<?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函数。我正在尝试这个,但没有得到任何答案。请建议你的答案。 请帮我这样做。

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

它不起作用,因为在双引号字符串the variables are stil evaluated中。您的代码应使用简单引号才能工作:

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

请注意,内部字符串仍应使用双引号,以便$x评估变量echo

答案 2 :(得分:1)

问题是你使用双引号。当双引号字符串经过评估阶段时,您的$ x变量将被解释 - 就像在原始回声中一样。

如果您将其更改为使用单引号,则应该有效:

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

以下是eval版本:

<?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>
相关问题