0

i am doing some oop in php and when i just wanted to know if its good to do this? when i use $this->functionName(), it works fine and i even tried with self:: and static:: and they work as i expected:

self:: will use the parent method implementation and static will use the last implementation of the method if overridden (late static binding). but the problem is that it is being used on a non static function. is this good? does it has any drawbacks?? why shouldn't i use it?

user2707590
  • 1,066
  • 1
  • 14
  • 28

1 Answers1

1

See this answer for detailed description.

In general, it is possible to do the things you describe and PHP allows it. But remember that people are used to polymorphism and method overridding so if your base class allows to override some method and then, uses a self to call it, it will be weird that I can't change the class behavior, although it exposes it in its API as public or protected method.

IMO, it violates the Principle of least astonishment, referenced in Uncle Ben's Clean Code book.

Also, there are some differences between static and $this bindings, because static will always try to reference the element in the narrower, not always appropriate scope. This behavior is presented in this example, and is explained in the note above, which I reference here:

In non-static contexts, the called class will be the class of the object instance. Since $this-> will try to call private methods from the same scope, using static:: may give different results. Another difference is that static:: can only refer to static properties.

Thus, although it is possible to use static in some places where $this is appropriate, the static keywords was introduced to use access static methods and fields and using it for another purposes should be considered confusing.

Community
  • 1
  • 1
fracz
  • 20,536
  • 18
  • 103
  • 149
  • this does not fully answer my question. we can use self::methodName() instead of $this->methodName()... but is it good to do that??? the problem of polymorphism will not arise if we use static::methodName() because it will be the same as $this->methodName... so why not self:: / static:: vs $this-> ??? – user2707590 Nov 02 '13 at 13:40
  • please see my edits as I provided more arguments against using `static` for non-static methods – fracz Nov 02 '13 at 16:25
  • @user2707590 Using the wrong accessor is not only confusing but also generates a warning message! – ComFreek Nov 02 '13 at 16:28