note 56227 added to function.include
| From: | navvywavvy at osu1 dot php dot net | Date: | Sat, 27 Aug 2005 21:53:56 +0000 |
| Subject: | note 56227 added to function.include | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-94278@lists.php.net to get a copy of this message | ||
In the documentation for include, they say that your included file will inherit the scope of the
line where it was included. In other words, if you include a file within a function, it has access
to all variables within that function, but no non-global variables outside that function.
I had a class definition, and in one of the methods I included a php file. However, when I tried to
access any of the properties of the class, it didn't work.
Example:
class MyClass {
var $SomeProperty;
// Constructor
function MyClass () {
$this->SomeProperty = "A string of words";
}
function DoSomething() {
$foo = "bar";
include("include_file.php");
}
}
The contents of "include_file.php" are:
<?php
echo($foo);
echo($this->SomeProperty);
?>
Now, if you instantiate that class and call the DoSomething method, you will see:
bar
Notice: Undefined variable: this in /path/to/include_file.php on line 3
What a disappointment. So what are the options? The only ones I can come up with are:
a) redefine all properties of the class inside the function as function-specific variables before
including your file and remove the "this->" from your included file.
b) remove the <?php and ?> lines from the file and use the file function to import the file
contents into an array. Then implode the array and call eval on the string.
Both solutions are pretty awful. (a) is potentially a hell of a lot of work, and with (b) you
can't ever break out of the php tags to write some plain html (all html will have to be echoed)
- and I bet (b) is way slower than just including a file, too.
If anyone has any ideas about how to better get around this issue, please post it.
----
Manual Page -- http://www.php.net/manual/en/function.include.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+56227
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+56227&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+56227&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+56227&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+56227&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+56227&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+56227&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+56227&report=yes
Search -- http://master.php.net/manage/user-notes.php