Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trying to understand late static bindings in php

Tags:

php

<?php
class Record {

    protected static $tableName = 'base';

    public static function getTableName() {
        echo self::$tableName;
    }
}
class User extends Record {
    protected static $tableName = 'users';
}
User::getTableName(); 

It shows: base

Question:

I know I can change the problem by changing this line echo self::$tableName; to echo static::$tableName;, it is called 'late static bindings', I read the doc here, but still not quite understand it. So could you give me some explanation on:

a. why this line of code echo self::$tableName; shows: base?

b. why this line of code echo static::$tableName; shows: users?

like image 850
user2294256 Avatar asked Jul 22 '13 07:07

user2294256


People also ask

What exactly are late static bindings in PHP?

PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance. More precisely, late static bindings work by storing the class named in the last "non-forwarding call".

What is early and late binding in PHP?

As of PHP 5.3. 0, PHP implements a feature called late static binding which can be used to reference the called class in the context of static inheritance. Late static binding tries to solve that limitation by introducing a keyword that references the class that was initially called at runtime. ...

Which version of PHP introduced the concept called late static binding?

This is called late static binding. This feature of late static binding was introduced in PHP 5.3 and above, previous versions will show a fatal error.

Can we override static method PHP?

Can we override a static method? No, we cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time.


1 Answers

The example below will give a minimum example of late static binding:

class A {
    static public $name = "A";

    static public function getName () {
        return self::$name;
    }

    static public function getNameLateStaticBinding () {
        return static::$name;
    }
}


class B extends A {
    static public $name = "B";
}



// Output: A
echo A::getName(), "\n";

// Output: A
echo B::getName(), "\n";

// Output: B
echo B::getNameLateStaticBinding() , "\n";

B::getName() outputs the $name variable from A since self is computed from the absolute current class you defined self in. To solve such cases, use static.

like image 197
Petter Kjelkenes Avatar answered Nov 15 '22 20:11

Petter Kjelkenes