0

How can I convert content of a one line string into a code, that actually executes? Lets say that I intend to run the following code:

<?php

$sum=0;
for($i=1;$i<11;$i++){
    $sum+=$i;
}

echo $sum;

?>

but part of the code is a content of a string $s:

<?php

$sum=0;
$s="for($i=1;$i<11;$i++){";

//what to write here to use the content of the string $s as a code
    $sum+=$i;
}

echo $sum;

?>

EDIT: I am dealing with the hypothetical question, the two source codes are just an illustration.

Jan
  • 55
  • 6
  • 2
    Hopefully you can't do this. – AymDev Nov 25 '21 at 15:09
  • 1
    That won't work. You could use `eval()`, but only for a syntactically sound part of your code, and only if you have any **really** good reason. So: **why** do you want to use this? – Nico Haase Nov 25 '21 at 15:09
  • This is a "hypothetical" question, not a real problem. – KIKO Software Nov 25 '21 at 15:10
  • You can just use $i directly, why would you need to put it in a string? Is `$i` the name of the variable? I don't see a real need for that. You can create a [function](https://www.php.net/manual/en/language.functions.php) which takes parameters for the loop. You can not use `eval()` here because your string is not valid PHP code. You may not execute *part* of a PHP statement within a string. Most code can be change to not depend on [the evil eval](https://stackoverflow.com/questions/951373/when-is-eval-evil-in-php). – Peter Krebs Nov 25 '21 at 15:16
  • The presented example code that adds numbers 1 to 10 is just an illustration. I am dealing with an abstract question. – Jan Nov 25 '21 at 15:35
  • And do you have any **specific** question? Maybe it's easier to answer that – Nico Haase Nov 25 '21 at 15:37
  • Here is a specific question: If I have a part of a php code saved as a content of a string, how do I execute that? – Jan Nov 25 '21 at 15:41
  • Please add all clarification to your question by editing it. Also, have you read the hints provided in the comment section? You **could** use `eval()` for this, but you should avoid it at all costs – Nico Haase Nov 25 '21 at 15:48
  • eval() is a new function to me. In this case I don't think that one can apply it, because the argument of eval() has to end with a semicolon. – Jan Nov 25 '21 at 16:29
  • That's true: `eval` can only be used with a sound part of the code, not with parts. There's no way something like the solely the `$s` string from your snippet could get evaluated to something meaningful. If the code is **always** a `for` loop, you could think about rewriting it to a `do {} while` loop and evaluate your condition in the `while` part – Nico Haase Nov 26 '21 at 06:48

0 Answers0