Skip to content

Instantly share code, notes, and snippets.

@sagormax
Last active December 8, 2020 05:20

Revisions

  1. sagormax revised this gist Dec 8, 2020. 1 changed file with 5 additions and 1 deletion.
    6 changes: 5 additions & 1 deletion late-static-binding.php
    Original file line number Diff line number Diff line change
    @@ -46,4 +46,8 @@ public static function stateName()

    echo EarlyBinding::show();
    echo "<br />";
    echo LateStaticBinding::get();
    echo LateStaticBinding::get();

    // << output >>
    // Undefined
    // Mohammad Bin
  2. sagormax created this gist Dec 8, 2020.
    49 changes: 49 additions & 0 deletions late-static-binding.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    <?php

    class User
    {
    public static $name = "Undefined";

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

    /**
    * Early binding
    *
    * @return string
    */
    public static function show()
    {
    return self::stateName();
    }

    /**
    * Late static binding
    *
    * @return string
    */
    public static function get()
    {
    return static::stateName();
    }
    }

    class EarlyBinding extends User {
    public static function stateName()
    {
    return "This static method should not be called...";
    }
    }

    class LateStaticBinding extends User {
    public static function stateName()
    {
    return "Mohammad Bin";
    }
    }

    echo EarlyBinding::show();
    echo "<br />";
    echo LateStaticBinding::get();