0

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.

7
  • you want to return the value in the function , not echo it Commented Jun 21, 2015 at 20:59
  • Both should echo perfectly fine. Commented Jun 21, 2015 at 21:01
  • I shouldn't need to return it; it's being assigned to a class variable. That's what $this->value = $included_value is supposed to do, right? Commented Jun 21, 2015 at 21:02
  • They should echo perfectly fine, but the one outside does not. Hence my confusion. :/ Commented Jun 21, 2015 at 21:02
  • By should, I meant that I tested it and it works fine (assuming you defined the class correctly in Object.php). Do you get any errors? Also, you should probably post your full, minimal, verifiable example. Commented Jun 21, 2015 at 21:05

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, but I'm calling echo outside the init(), using an object reference. So, echo $object->value.
The variable $included_value is not referenced prior to the include statement so does not exist when include is invoked.
the variable $included_value is inside the included file.
Yes, so all functions and classes defined in the included file have the global scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.