Skip to content

Instantly share code, notes, and snippets.

@Jeff-Russ
Last active January 4, 2017 09:09
Show Gist options
  • Save Jeff-Russ/02ae39994666776546b5852e57d99423 to your computer and use it in GitHub Desktop.
Save Jeff-Russ/02ae39994666776546b5852e57d99423 to your computer and use it in GitHub Desktop.
PHP: Static Method Chaining
<?php
class One {
    static function echoGetClass() { echo get_class()."\n"; }
    
    private static $it;
    # chaining is possible if you return the class name! ...
    static function setIt($it)  { One::$it = $it; return 'One';}
    static function echoIt()    { echo One::$it;  return 'One';}
    
    static function returnGetClass()    { return get_class(); }
    static function returnCalledClass() { return get_class(); }
    static function echoCalledClass()   { echo get_called_class()."\n";  }
    
    
    public static $class;
    public static $static;
    static function init() {
        One::$class  = get_class();
        One::$static = get_called_class();
    }
    static function echoInitClass() { echo One::$class."\n"; }
    static function echoInitStatic(){ echo One::$static."\n"; }
}

One::echoGetClass(); # echoes: One

$classname = One::setIt("IT!\n")::echoIt(); # chaining possible because setIt returns 'One'
echo "\$classname is $classname\n";

$classname::returnGetClass()::returnCalledClass()::echoCalledClass(); # also echoes: One

class Two extends One {}

One::init(); # called on One so it can't get inherited class name 

One::echoInitClass();  # echoes: One
Two::echoInitStatic(); # !!! echoes: One

Two::init(); # this time it works to get correct static class name

One::echoInitClass();  # echoes: One
Two::echoInitStatic(); # NOW echoes: Two

OUTPUT:

One

IT!
$classname is One

One

One
One

One
Two
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment