trying to understand late static bindings in 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 can change problem changing line echo self::$tablename; echo static::$tablename;, called 'late static bindings', read doc here, still not quite understand it. give me explanation on:

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

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

self "bound" @ compile time, statically. means when code compiled, decided self refers to. static resolved @ run time, i.e. when code executed. that's late static binding. , that's difference.

with self, decided @ compile time (when code "read"), self refers record. later on code user parsed, self::$tablename in record refers record::$tablename , cannot changed anymore.

when use static, reference not resolved immediately. resolved when call user::gettablename(), @ point you're in context of user, static::$tablename resolved user::$tablename.

in other words: self refers class has been written in, no 2 ways it. static refers depends on context it's used in; in practice means may refer child classes if class occurs in being extended. makes work $this, static contexts.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -