Saturday, November 9, 2019

What exactly are late static bindings in PHP?

I'm quoting from the book: "PHP Master write cutting-edge code".





Late static binding was a feature introduced with php 5.3. It allows
us to inherit static methods from a parent class, and to reference
the child class being called.



This means you can have an abstract class with static methods, and
reference the child class's concrete implementations by using the
static::method() notation instead of the self::method().





Feel free to take a look at the official php documentation as well:
http://php.net/manual/en/language.oop5.late-static-bindings.php






The clearest way to explain Late Static Binding is with a simple example. Take a look at the two class definitions below, and read on.



class Vehicle {
public static function invokeDriveByStatic() {

return static::drive(); // Late Static Binding
}
public static function invokeStopBySelf() {
return self::stop(); // NOT Late Static Binding
}
private static function drive(){
return "I'm driving a vehicle";
}
private static function stop(){
return "I'm stopping a vehicle";

}
}

class Car extends Vehicle {
protected static function drive(){
return "I'm driving a CAR";
}
private static function stop(){
return "I'm stopping a CAR";
}

}


We see a Parent Class (Vehicle) and a Child Class (Car).
The Parent Class has 2 public methods:




  • invokeDriveByStatic

  • invokeStopBySelf




The Parent Class also has 2 private methods:




  • drive

  • stop



The Child Class overrides 2 methods:





  • drive

  • stop



Now let's invoke the public methods:




  • invokeDriveByStatic

  • invokeStopBySelf




Ask yourself: Which class invokes invokeDriveByStatic / invokeStopBySelf? The Parent or Child class?



Take a look below:



// This is NOT Late Static Binding
// Parent class invokes from Parent. In this case Vehicle.
echo Vehicle::invokeDriveByStatic(); // I'm driving a vehicle
echo Vehicle::invokeStopBySelf(); // I'm stopping a vehicle


// This is Late Static Binding.
// Child class invokes an inherited method from Parent.
// Child class = Car, Inherited method = invokeDriveByStatic().
// ...
// The inherited method invokes a method that is overridden by the Child class.
// Overridden method = drive()
echo Car::invokeDriveByStatic(); // I'm driving a CAR

// This is NOT Late Static Binding

// Child class invokes an inherited method from Parent.
// The inherited method invokes a method inside the Vehicle context.
echo Car::invokeStopBySelf(); // I'm stopping a vehicle





The static keyword is used in a Singleton design pattern.
See link: https://refactoring.guru/design-patterns/singleton/php/example

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...