Reputation: 344
I came across some code today that uses PHP's late static binding and the way it's used doesn't make sense to me. Late static binding is a new concept for me so I'm trying to wrap my head around it.
After studying this Github Gist and reading this Stack Overflow post, I understand what late static binding does and why it's used. Now I'm trying to apply that to the code I'm looking at and it doesn't make sense to me. It feels like the static
keyword is being used incorrectly. Here's more or less the code I'm not sure about:
<?php
class myClass
{
const MY_CONST = 'some string';
public function getMyConst()
{
return static::MY_CONST;
}
}
$c = new myClass();
print_r($c->getMyConst());
Assuming I'm understanding the concept, late static binding let's you reference a child's const in a static context. So in the code I'm looking at there's no inheritance and there's no static function, so what is the point of using the static
keyword vs the self
keyword in this particular use case? Also, does it hurt anything to use the static
keyword in this way, assuming that it's being used incorrectly (or maybe not exactly as it was intended to be used)?
Upvotes: 1
Views: 261
Reputation: 20286
In this particular case using $c::MY_CONST
, self::MY_CONST
, static::MY_CONST
, myClass:MY_CONST
will have the same effect. But look your class is not declared as final and can be extended and when it's extended static keyword will point to the const using late binding.
Using a late binding always come with the cost, but come on it's not C++, you don't program a driver on low level with low resources. The cost won't be noticeable at all. However, not using static may lead to some hard to detect bugs in the future.
In PHP manual you can also find interesting thing about late binding in PHP
Late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the :: operator); in case of non static method calls, it is the class of the object.
This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact that static:: will not be resolved using the class where the method is defined but it will rather be computed using runtime information.
Upvotes: 1