Early and Late static binding in PHP. Code example open

Early and Late static binding in PHP. Code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: PHP 7
class Transport{
  public static $model = 'transport';
  public static function getModel() {
    return self::$model;
  }
}

class Car extends Transport{
  public static $model = 'car';
}

echo Car::getModel(); // 'transport'

return self::$model – points to the current class, so the result is ‘transport’, this mechanism is also called “Early static binding“.

class Transport{
  public static $model = 'transport';
  public static function getModel() {
    return static::$model;
  }
}

class Car extends Transport{
  public static $model = 'car';
}

echo Car::getModel(); // 'car'

If the word “self” is replaced by “static“, then we get “late static binding“, i.e. the connection will be established with the class that calls this code, as a result we get the value “car”.

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation