3

I'm just asking based on experience with other languages that can disambiguate method calls from global function calls based on class scope - eg:

class Foo {
 function bar(){
   echo 'bletch';
 }

 function baz(){
   $this->bar();
 }
}

So I guess I'm asking whether there's another way of doing $this->bar(), or in other words, how can I leave out $this, which just seems redundant given the context?

Tom Auger
  • 19,421
  • 22
  • 81
  • 104

2 Answers2

4

No, you can't access bar() from within baz() without $this-> in PHP as you can easily have global function bar() that is not part of any class/object (which is the difference then most of those languages you are reffering to), which would result in collision.

ddinchev
  • 33,683
  • 28
  • 88
  • 133
  • One could use `self::` instead of `$this->`, as stated in http://stackoverflow.com/questions/151969/php-self-vs-this – Diego Agulló Jul 18 '12 at 15:04
  • 2
    `self::` operator is accessing the class itself (static methods, properties and constants that belong to the class), while `$this->` is accessing the instance (instance methods and properties like in the case of the question). – ddinchev Jul 18 '12 at 15:08
  • Thanks, just checking. Other languages can disambiguate from global scope functions based on the class scope (favoring whichever method / function has the tightest scope). I wonder whether formal namespacing could help here, but frankly it's probably not worth the headache either way. Just checking in case there was a trick I had missed along the way. – Tom Auger Jul 19 '12 at 13:21
0

In short it is not posible.

because calling bar would call a function named bar outside the class given the following:

function bar() {
 echo 'foo';
}

class Foo {
 function bar(){
   echo 'bletch';
 }

 function baz(){
   $this->bar();
 }

 function foobar() {
   bar();
 }
}

$instance = new Foo();

$instance->foobar();

this would echo foo of the function bar() instead of bletch of the method bar()

FLY
  • 2,379
  • 5
  • 29
  • 40