mardi 26 janvier 2016

How do "static" keyword works? (a code example)

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 dont work.

Do someone help me with static understanding? I dont know, why it doesn't work.

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();

Aucun commentaire:

Enregistrer un commentaire