Jump to content

Variables scope in included files


Manaus
 Share

Recommended Posts

Hello,

since include is sort of copy'n'pasting code in the calling file, I might have variables value overwriting.

Is it possible to have variables valid for the included file alone? Something like $this->title etc?

Thanks!

Link to comment
Share on other sites

Hi,

http://php.net/manual/en/function.include.php

"When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope."

"Is it possible to have variables valid for the included file alone?"

So I suppose the answer is no.

  • Like 1
Link to comment
Share on other sites

included_file.php

<?php
$fruit = 'banana';
echo "<p>My fruit is a $fruit</p>";

main.php

<?php
$fruit = 'watermelon';
call_user_func( function() {
    return include func_get_arg(0);
}, 'included_file.php' );
echo "<p>My fruit is a $fruit</p>";

Output:

<p>My fruit is a banana</p>
<p>My fruit is a watermelon</p>

Credit

  • Like 5
Link to comment
Share on other sites

@Robin - I have to confess, my head hurt a little bit after reading over the post you credited :) Very interesting stuff though, Thank you for sharing that.
 

@Manaus - Can you wrap the code/variables in your include, which you are concerned about , within a class? Maybe I'm missing something in your question,  but if you're looking to be able to use variables within the include in this manner - $this->title, then I believe $title needs to be defined within a Class http://stackoverflow.com/questions/1523479/what-does-the-variable-this-mean-in-php 

Might help if sample code was provided with the question ? 

Have a good one.

Link to comment
Share on other sites

When working with Namespaces, (PW3), it is allowed to use different namespaces in one file. Assuming you have a php file you want to include with this code:

<?php
echo "<p>I love $var!</p>";

you can have a template file like this:

<?php
namespace ProcessWire {
    // ...
}
namespace fake1 {
    $var = 'apples';
    include('./_namespace-include-test.php');
}
namespace fake2 {
    $var = 'bananas';
    include('./_namespace-include-test.php');
}
namespace ProcessWire {
    $var = 'oranges';
    include('./_namespace-include-test.php');
    // ...
}

The output will be: 

I love apples!

I love bananas!

I love oranges!

Why and how this works is in the PHP manual. There you also can read that this is bad practice. :)

  • Like 6
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...