2011-05-02 113 views
0
class Foo { 
    public static function foobar() { 
    self::whereami(); 
    } 
    protected static function whereami() { 
    echo 'foo'; 
    } 
} 
class Bar extends Foo { 
    protected static function whereami() { 
    echo 'bar'; 
    } 
} 

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

預期的結果foobar實際結果foofoo擴展在PHP

更糟糕的是靜態方法,服務器被限制在PHP 5.2

+2

PHP 5.3引入了[後期靜態綁定](http://php.net/manual/en/language.oop5.late-static-bindings.php)。看起來你可能會運氣不好,5.2 – Phil 2011-05-02 04:10:12

回答

0

這篇文章涵蓋了它相當不錯:Why does PHP 5.2+ disallow abstract static class methods?

+0

所以我假設如果我必須這樣做,我有一些非常醜陋的髒編碼做... – 2011-05-02 04:04:33

+0

呃。猜猜你只需要重新思考你的課堂! – 2011-05-02 05:10:19

0

難道你不需要覆蓋父函數foobar()嗎?

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

嘗試使用Singleton模式:

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


?> 
2

所有你需要的是一個一個字的變化!

的問題是在方法調用WHEREAMI(),而不是自我::你應該使用靜::。因此類美孚應該是這樣的:

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

在另一個字,「靜態」實際上使調用WHEREAMI()動態:) - 這取決於調用什麼類