PHP Late Static Binding Explained

Atakan Demircioğlu
Jotform Tech
Published in
2 min readJul 4, 2023

--

Here’s an interesting topic that I learned about in a surprising way while coding.

Late static binding

Before we start, let’s clarify some terms:

  • Late static binding (LSB) is the combination of late binding and static binding, two different concepts.
  • Static, in a very short summary, refers to making static calls when you don’t need any object creation.
  • Static binding (early binding) happens at compile time.

What is Static Binding?

Static binding refers to the process of resolving static method calls at compile-time. When a method is declared as static, it means that the method belongs to the class itself rather than an instance of the class.

Static binding is used when the method is called and is known at compile-time, based on the class from which the call is made. The decision of which method to call is made during the compilation phase, and the appropriate method is bound to the call.

What is PHP late static binding?

When a static method is called from a subclass that overrides the method, the static binding refers to the class where the method is called, rather than the class in which it is defined.

Let’s continue with an example

<?php

class Model
{
protected static $table = 'Model';

public static function getTable()
{
return self::$table;
}
}

class User extends Model
{
protected static $table = 'User';
}

echo User::getTable();

Most devs just think this will output “User.” But this will output “Model” because of self-keyword behavior.

The reason is that self is resolved to the class to which the method belongs.

To resolve this issue, PHP 5.3 introduced late static binding and used the static keyword for solving this issue. If you replace the self keyword with the static keyword, that will reference the exact class.

<?php

class Model
{
protected static $table = 'Model';

public static function getTable()
{
return static::$table;
}
}

class User extends Model
{
protected static $table = 'User';
}

echo User::getTable();

Now you will get the expected result.

Atakan Demircioğlu is a Full Stack Developer currently working at Jotform, a leading online form-builder platform.

He is passionate about blogging, learning, and creating. He shares his experiences on Medium and GitHub.

Twitter: https://twitter.com/atakde

Github: https://github.com/atakde

Buy me a coffee if you liked the content.

--

--

Passionate about blogging and sharing insights on tech, web development, and beyond. Join me on this digital journey! 🚀