Reputation: 99
Inside a class, I have a method that reads a few variables from an external file. I then set member variables using these included variables. As soon as this method completes however, the member variables get reset to null. What am I doing wrong?
main.php
$bob = new Object();
$bob->init();
echo $bob->value;
Object.php
public function init() {
include('/includefile.inc');
$this->value = $included_value;
echo $this->value;
}
includefile.inc
<? $included_value = 'Hello World'; ?>
The echo inside Object.php will work correctly, but the echo outside in main will be null. value is a public variable inside the Object.php class definition.
Upvotes: 0
Views: 1381
Reputation: 48357
Quoted directly from the manual...
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.
Hence....
public function init() {
$included_value=false;
include('/includefile.inc');
$this->value = $included_value;
echo $this->value;
}
Should work as you expect.
Upvotes: 1