开发者

extending static methods in php

class Foo {
  public static function foobar() {
    self::whereami();
  开发者_JAVA百科}

  protected static function whereami() {
    echo 'foo';
  }
}

class Bar extends Foo {
  protected static function whereami() {
    echo 'bar';
  } 
}

Foo::foobar();
Bar::foobar();

expected result foobar actual result foofoo

to make matters worse, the server is restricted to php 5.2


All you need is a one-word change!

The problem is in the way you call whereami(), instead of self:: you should use static::. So class Foo should look like this:

class Foo {
  public static function foobar() {
    static::whereami();
  }
  protected static function whereami() {
    echo 'foo';
  }
}

In another word, 'static' actually makes the call to whereami() dynamic :) - it depends on what class the call is in.


Try to use singleton pattern:

<?php

class Foo {
    private static $_Instance = null;

    private function __construct() {}

    private function __clone() {}

    public static function getInstance() {
        if(self::$_Instance == null) {
            self::$_Instance = new self();
        }
        return self::$_Instance;
    }

    public function foobar() {
        $this->whereami();
    }

    protected function whereami() {
        print_r('foo');
    }
}
class Bar extends Foo {
    private static $_Instance = null;

    private function __construct() {}

    private function __clone() {}

    public static function getInstance() {
        if(self::$_Instance == null) {
            self::$_Instance = new self();
        }
        return self::$_Instance;
    }

    protected function whereami() {
        echo 'bar';
    } 
}

Foo::getInstance()->foobar();
Bar::getInstance()->foobar();


?>


Don't you have to overwrite the parent function foobar() too?

class Foo {
  public static function foobar() {
    self::whereami();
  }
  protected static function whereami() {
    echo 'foo';
  }
}
class Bar extends Foo {
  public static function foobar() {
    self::whereami();
  }
  protected static function whereami() {
    echo 'bar';
  } 
}

Foo::foobar();
Bar::foobar();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜