PHP Late Static Binding

Created with Sketch.

PHP Late Static Binding

Summary: in this tutorial, you will learn about the PHP late static binding, which is an interesting feature that has been added to the PHP 5.3

Introduction to late static binding in PHP

Let’s start with a simple example.

<?php

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

public static function getTableName()
{
return self::$tableName;
}
}

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

echo User::getTableName(); // Model, not User

Code language: HTML, XML (xml)

How it works.

  • First, create a Model class that has $tableName static property with the value Model and a getTableName() static method that returns the value of the $tableName.
  • Second, create another class called User that extends the Model class. The User class also has $tableName static attribute.
  • Third, call the getTableName() method of the User class. However, it returns Model instead of User. The reason is that self is resolved to the class in which the method belongs. If you define a method in a parent class and call it from a subclass, it self does not reference the subclass as you might expect.

To resolve this issue, PHP 5.3 introduced a new feature called PHP static late binding.

Instead of using the self, you use the static keyword that references an exact class that is called at runtime.

Let’s modify our example above:

<?php

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

public static function getTableName()
{
return static::$tableName;
}
}

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

echo User::getTableName(); // User

Code language: HTML, XML (xml)

Now you get the expected result.

Leave a Reply

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