static and self: weird behaviour or not

Posted on July 1, 2016, 6:00 pm by about-dev.com


Reading the code below, what do you think it will be the output? It has been tested using PHP 5.5.30.

error_reporting(E_ALL & ~E_STRICT);

class ClassTarget
{
 private static $propertyA = 1;

 public function getStatic()
 {
  return static::$propertyA;
 }

 public function getSelf()
 {
  return self::$propertyA;
 }
}

class Caller
{
 public static $propertyA = 2;

 public function getStatic()
 {
  return ClassTarget::getStatic();
 }

 public function getSelf()
 {
  return ClassTarget::getSelf();
 }
}

echo 'static call = ' . (new caller())->getStatic();
echo 'self call = ' . (new caller())->getSelf();

If you think that you have guess right the answer, check again and see there is no inheritance between the 2 classes. So, I don't think that Late static binding is the reason.

static call = 2
self call = 1

Indeed, the code have the same result as the Caller class is extending the ClassTarget. But why? ClassTarget is borrowing a property from Caller even if there is no relation between those 2?


Leave a Comment:

User
Email
Website

Blog Search

Popular Blog Categories

Newsletter

Want to be informed about latest posts? Subscribe to our newsletter