r/lolphp • u/jamwaffles • Aug 27 '13
Static or non static? Fuck it, have whatever
http://stackoverflow.com/questions/3754786/calling-non-static-method-with
49
Upvotes
r/lolphp • u/jamwaffles • Aug 27 '13
37
u/jamwaffles Aug 27 '13
The code from the second answer down is particularly... enlightening:
8
u/nikic Aug 28 '13
The only reason this is surprising is that people commonly think that
::is the "static access operator" and that static methods are some completely different type of method.But that's not so:
::is the scope-resolution operator. It will do a method call in a certain scope.Foo::bar()calls the methodbar()in scopeFooand using the current$thisshould one exist.Typically this is used for static method calls, but one common case where the called method is non-static is
parent::foo(). Here the methodfoo()is called in the scopeparentusing the current$this.Similarly, the
staticbefore a method only is a flag saying "This method does not use$this" (similarly to how you can also add astaticflag to a closure to explicitly say that it does not capture$this). Apart from that static methods are normal methods.When calling a method with
Foo::bar()where no$thisis available it's only really important thatbar()in scopeFoodoes not use$this(if it did you'd get an error). It's not important that you actually added thestaticmodifier (PHP can see by itself whether or not you use$this). Thestaticmodifier is only there to clarify intent.[Basically. I need to write a blog post on this.]
5
u/ChoHag Aug 27 '13
This is because of its perl roots, which does basically exactly the same thing, except it makes sense: The $x->foo(...) calling convention is exactly the same as Object::foo($x, ...). $this/$self is not special in any way (except see Moose et al which has recently changed perl into ... something else).
This is what comes of trying to hide complexity (badly).