Jump to content

Scope problem within constructor


Jack McKalling

Recommended Posts

As I am developing a module for my website, fully in OOP, I am confronted with an unexpected scope resolution inconsistancy or something.It comes down to my hypothesis that, when instantiating a class by a local static method, the scope of the constructor is not within the static method, but where that static method was called.This is a simplified example that illustrates the problem:

<?phpclass Test{   protected function __construct()  { global $var;    echo "\$var = $var";  }  public static function createInstance()  { return new self();  }}$var = "testing.";$obj = Test::createInstance();?>

This calls the constructor within the static method, so I would expect "global $var" in the constructor, to look for the var in the static method's scope. Eventhough I don't forward the variable there, it is still availlable in the constructor. See that this outputs:

$var = testing.
May I conclude that the constructor gets called from the global scope, regardless of the static method?Or does it have something to do with the fact that it is a magic method, or that I'm using the keyword self?
Link to comment
Share on other sites

It has to do with the fact that you're specifically telling it to use the global value of $var, which you define in the global scope. If you removed the global declaration from the constructor then you would not see it print the value of the global variable, it would issue a notice that $var is undefined. It's only finding the value because you're explicitly telling it to use the global value. There's only one global scope, there's not a global scope for the script, then another global scope for the static method, then another global scope for the constructor. There's only one global scope, everything else is a local scope.

Link to comment
Share on other sites

Ok, that figures. I also have an autoloader, but for that I do need the global keyword in the autoloader, to make the var(s) available inside the included file. But I see that's because of the way the include() works.So I really only need to use the global keyword in the last method in a series, if I want to use a variable from global scope? Hmm interesting, this teaches me alot about the keyword. I'm used to Java's OOP, and using this keyword is kind of like, strange. But convenient nevertheless! :)

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...