Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP eval() function
    text
    copied!<p>The PHP function eval() appears to be a rather interesting function. Can someone explain why it works in this given situaton, on line: 14</p> <p> <pre><code>function Parse($inFrontEnd) { // Now create an array holding translation tokens with some from above // Load translation table into buffer $tableLines = file(Utilities::GetRelativePath(TTABLE_DIR).TTABLE); // Array of lines from TTable.cfg // Explode by whitespace foreach($tableLines as $aLine) { $lineParts = EXPLODE(' ', $aLine); $word = "/".$lineParts[0]."/"; $definition = $lineParts[1]; // Add key (word) =&gt; value (definition) to array // Eval() to return value of the const Main::$translateChars[$word] = eval("return $definition;"); } // Read data from template file $parseArray = file($inFrontEnd); // Load FrontEnd source code into array ready for parse /* Perform the translation of template by the translation table defined data */ $parseArray = preg_replace(array_keys(Main::$translateChars), array_values(Main::$translateChars), $parseArray); return $parseArray; } </code></pre> <p></p> <p>So what I'm doing here is reading in a template from a template directory. The templatename.php file comprises of text tokens written constant-like, which are then translated by regular expressions replacing the tokens with the data the constants with their names hold, thus returning a fully validated page of a webpage, which is printed for the user to view. This allows pages to be very dynamic by allowing the reuse of these tokens over many webpages (templates).</p> <p>My question is: I had trouble for a while with the line that uses eval(). What I'm trying to do there is fill an array with each key being the name of the constant read in from, what I've named, the translation table (TTable.cfg), which holds the name of each token and the constant associated with it:</p> <p>TITLE TITLE<br> CSS_INCLUDE CSS_INCLUDE<br> SHOW_ALL_POSTS SHOW_ALL_POSTS<br> ...</p> <p>So with the protocol [TOKEN] [CONSTANT][CR][LF]</p> <p>The keys within the array would be created fine, but the values would return null or break my code when I had the key be associated with: constant($definition); It complained it couldn't find the constants being declared. However, when I use eval as is on this line, each key associated with: eval("return $definition;"); it works as I want it - the values as their corresponding constant's data.</p> <p>I do apologise for the length of this post. I couldn't find any other example for my question other than the case I found it in.</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