Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>My initial response is to say there's virtually 0 good reason to create a function in eval. </p> <p>You can create functions conditionally, ie: </p> <pre><code>if ( $cond ){ function foo(){ } } </code></pre> <p>If you want <strong>closure</strong> like behaviour I guess eval is the only way to do it until PHP5.3, but its <em>EPIC</em> bad stuff and you should avoid it all cost. </p> <p>Here is why:</p> <pre><sub> <b>01</b> &lt;?php <b>02</b> <b>03</b> function foo () <b>04</b> { <b>05</b> eval( ' <b>06</b> function baz() <b>07</b> { <b>08</b> eval("throw new Exception();"); <b>09</b> } <b>10</b> '); <b>11</b> baz(); <b>12</b> } <b>13</b> <b>14</b> <b>15</b> <b>16</b> try{ <b>17</b> foo(); <b>18</b> }catch( Exception $e ){ <b>19</b> var_dump($e); <b>20</b> } <b>21</b> try{ <b>22</b> foo(); <b>23</b> } <b>24</b> catch( Exception $e ){ <b>25</b> var_dump($e); <b>26</b> } </sub></pre> <p>Which Emits this: </p> <pre><sub> object(Exception)#1 (6) { ["message:protected"]=> string(0) "" ["string:private"]=> string(0) "" ["code:protected"]=> int(0) ["file:protected"]=> string(50) "/tmp/xx.php(10) : eval()'d code(4) : eval()'d code" ["line:protected"]=> int(1) ["trace:private"]=> array(3) { [0]=> array(3) { ["file"]=> string(31) "/tmp/xx.php(10) : eval()'d code" ["line"]=> int(4) ["function"]=> string(4) "eval" } [1]=> array(4) { ["file"]=> string(11) "/tmp/xx.php" ["line"]=> int(11) ["function"]=> string(3) "baz" ["args"]=> array(0) { } } [2]=> array(4) { ["file"]=> string(11) "/tmp/xx.php" ["line"]=> int(17) ["function"]=> string(3) "foo" ["args"]=> array(0) { } } } } Fatal error: Cannot redeclare baz() (previously declared in /tmp/xx.php(10) : eval()'d code:2) in /tmp/xx.php(10) : eval()'d code on line 5 Call Stack: 0.0002 115672 1. {main}() /tmp/xx.php:0 0.0006 122304 2. foo() /tmp/xx.php:22 </sub></pre> <p>So much badness, so little effort. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload