2011-05-02 109 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()动态:) - 这取决于调用什么类