note 56227 deleted from function.include by aidan

From: Date: Sat, 15 Apr 2006 16:33:49 +0000
Subject: note 56227 deleted from function.include by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-108159@lists.php.net to get a copy of this message
Note Submitter: navvywavvy ---- 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.

« previous php.notes (#108159) next »