0

When I tried to create C and B in global namespace - it did work correctly. When I turn B::create_unit() into body of C::create_unit() -> it becomes broken and won't work. Can anyone provide some insight about why this might be?

Class A {
  protected static $_instance;
  public $methods = array();

  public function __call($name, $args) {
    $obj = $this->methods[$name]['obj'];
    $method_name = $this->methods[$name]['method_name'];
    call_user_func_array(array($obj, $method_name), $args);
  }

  public static function add_method($name, $obj, $method_name) {
    $unit = static::get_unit();
    print_r($unit); // OMG, IT PRINTS (OBJECT B)!!!
    $unit->methods[$name]['obj'] = $obj;
    $unit->methods[$name]['method_name'] = $method_name;
  }

  public static function create_unit() {
    return static::$_instance = new static();
  }

  public static function get_unit() {
    return static::$_instance;
  }
}
Class B extends A {
  public static function create_unit() {
    return static::$_instance = new static();
  }
  public function log($msg) {
    echo $msg;
  }
}
Class C extends A {
  public static function create_unit() {
    $obj = static::$_instance = new static();
    $b = B::create_unit();
    C::add_method('foo', $b, 'log');
    $obj->foo('message');
    return $obj;
  }
}
C::create_unit();
PsiX
  • 1,661
  • 1
  • 17
  • 35
gzhegow
  • 53
  • 4
  • Provide all the messages next to the code you're using while asking for help.. "becomes broken and won't work" is 100% not what PHP told you. – Mjh Jan 27 '16 at 11:13

1 Answers1

0

self refers to the same class in which the new keyword is actually written.

static, in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on.

Try using self instead

self::get_unit();

Checkout self vs static

Community
  • 1
  • 1
Basheer Kharoti
  • 4,202
  • 5
  • 24
  • 50