Skip to content

Instantly share code, notes, and snippets.

@dongilbert
Created June 11, 2013 21:16
Show Gist options
  • Save dongilbert/5760779 to your computer and use it in GitHub Desktop.
Save dongilbert/5760779 to your computer and use it in GitHub Desktop.
PHP Scope Issues? or is this expected? I don't understand why the `$this` in `Foo::bar()` is being treated as though it is referencing the `$bar` instance. If I declare `Foo::bar()` as static, then I get the expected error of `Using $this when not in object context.` How can you call a method from another object if `$this` in that object refers …
<?php
class Foo
{
public function bar()
{
return $this->baz();
}
public function baz()
{
return 'buz';
}
}
class Bar
{
public function test()
{
return Foo::bar();
}
}
$bar = new Bar;
echo $bar->test();
?>
Outputs the following:
PHP Fatal error: Call to undefined method Bar::baz() in php shell code on line 1
@dongilbert
Copy link
Author

I ended up doing something similar to your second suggestion to fix it. I just thought it was very strange that $this within Foo::bar() was referencing the $bar instance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment