Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Firstly, PHP doesn't support nested functions in the way you are trying to use them. </p> <p>You can write this:</p> <pre><code>function outer() { function inner() {} } outer(); </code></pre> <p>But all that happens is that when <code>outer();</code> is executed, the <code>inner()</code> function is declared as a normal function. So the code is exactly the same as this:</p> <pre><code>function outer() {} function inner() {} outer(); </code></pre> <p>Secondly, variables in PHP (unless prefixed, with a class or object name) are always scoped to the current function. The <code>global</code> keyword <em>imports a reference</em> to a global variable into the current function's scope; it cannot be used to <em>export</em> a variable which was already defined. </p> <p>It is generally best to only use the <code>global</code> keyword at the very beginning of a function, to import all the global variables needed by that function. Even better, do not use global variables, since they lead to "spaghetti code" which is hard to understand and debug.</p> <p>If you declare the variable <code>global</code> <em>before</em> running <code>extract</code>, this will work, but <strong>I would strongly advise against using either feature</strong>.</p> <pre><code>function foo_with_too_much_magic() { // Import global variable. Very hard to track where this came from. global $some_var; // Let's assume this array comes from somewhere and isn't hard-coded $some_array = array('some_var' =&gt; 'some_value'); // Export variables from an array. This is like telling PHP to write different code each time it runs, with different variable names. extract( $some_array ); } foo_with_too_much_magic(); var_dump($some_var); </code></pre> <p>Here is a version of the above without the discouraged features:</p> <pre><code>function foo_with_no_magic() { // Let's assume this array comes from somewhere and isn't hard-coded $some_array = array('some_var' =&gt; 'some_value'); // You know which variable you want, so don't need the magic "export" // Note that you don't have to call it $some_var $some_var = $some_array['some_var']; // Now you have the variable, you can manipulate it, pass it to another function, or return it // In fact, you could also return $some_array['some_var'] directly, without the extra assignment return $some_var; } // This variable name no longer needs to be the same as what was used in the foo_with_no_magic() function $some_var = foo_with_no_magic(); var_dump($some_var); </code></pre>
 

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