Note that there are some explanatory texts on larger screens.

plurals
  1. POGiving PHP include()'d files parent variable scope
    text
    copied!<p>Is there anyway to for an included file to be used in a parent scope to the one it was called in? The following example is simplified, but does the same job.</p> <p>In essence, a file will be included by a function, but would like the scope of the included file to be the scope of where the function that included it was called from.</p> <p>main.php:</p> <pre><code>&lt;?php if(!function_exists('myPlugin')) { function myPlugin($file) { if(file_exists($file) { require $file; return true; } return false; } } $myVar = 'something bar foo'; $success = myPlugin('included.php'); if($success) { echo $myResult; } </code></pre> <p>included.php:</p> <pre><code>&lt;?php $myResult = strlen($myVar); </code></pre> <p>Thanks in advance,<br> Alexander.</p> <h2>EDIT: Solution</h2> <p>Well, sort of, thanks to the contributions by Chacha102.<br> Can be called from within a class now too!</p> <p>main.php</p> <pre><code>&lt;?php class front_controller extends controller { public function index_page() { $myVar = 'hello!'; // This is the bit that makes it work. // I know, wrapping it in an extract() is ugly, // and the amount of parameters that you can't change... extract(load_file('included.php', get_defined_vars(), $this)); var_dump($myResult); } public function get_something() { return 'foo bar'; } } function load_file($_file, $vars = array(), &amp;$c = null) { if(!file_exists($_file)) { return false; } if(is_array($vars)) { unset($vars['c'], $vars['_file']); extract($vars); } require $_file; return get_defined_vars(); } </code></pre> <p>included.php:</p> <pre><code>&lt;?php $myResult = array( $myVar, $c-&gt;get_something() ); </code></pre> <p>If you want to reference a method it has to be public, but the result is as expected:</p> <pre><code>array(2) { [0]=&gt; string(6) "hello!" [1]=&gt; string(7) "foo bar" } </code></pre> <p>Now, this doesn't really have any practical use, and the only reason I wanted to know how to do this is because I am stubborn. The thought came into my head, and would not let it defeat me :D</p> <p><code>&lt;rant&gt;</code><br> Thanks to all who contributed. Except the person who boo'd me. It was a simple enough question, and have now figured out that (complicated) solution exists.<br> Screw whether it "conforms to the PHP way of doing things". Ever told a client "Oh no, we shouldn't do that, it's not the correct way to do things!"? Thought not.<br> <code>&lt;/rant&gt;</code></p> <p>Thanks again to Chacha102 :)</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