2011-02-26 68 views
1

我有很好的oop理解,但在php中對其實現的理解很差...PHP5靜態方法的繼承。超載。獲取所謂的類名

我有以下代碼,希望它的自我記錄=)。

我需要有BB輸出

class A{ 
    // I can't copy function::classname() to all my descendant classes 

    static function classname(){ 
     echo __CLASS__; 
    } 
} 

class B extends A{ 

    static function test(){ 
     self::classname(); 
    } 

    function test1(){ 
     self::classname(); 
    } 



    //i have A LOT of static and non-static functions using self::classname() in their code 
    // I can't copy all them to base class 
    } 

    $v = new B(); 
    B::test(); 
    $v->test1(); 

我堅持用static::self::語法


PS:另一種瘋狂的問題我遇到:

假設我有

function doSomething(){ 
    echo $this->id; 
} 

有時會進入靜態環境。是的,我知道,那是因爲我的糟糕的應用程序設計。但是它可能建立一個第二(反射鏡,超載)函數

static function doSomething(){ 
    echo false; 
} 

這意味着使用 $obj->doSomething()返回id和使用Class::doSomething()返回false


問題3:

是它可能在靜態上下文中獲取屬性默認值自動在非靜態上下文中獲取屬性值?

回答

5

看看late static binding

class A { 
    static function classname() { 
     echo __CLASS__; 
    } 

    static function test1() { 
     static::classname(); 
    } 
} 

class B extends A { 
    static function classname() { 
     echo __CLASS__; 
    } 
} 

$v = new B(); 
B::test1(); 
$v->test1(); 

或由耳朵長在評論指出,假設PHP 5.3.0+您可以使用get_called_class()

class A { 
    static function classname() { 
     echo get_called_class(); 
    } 

    // this can be defined in either class A or B without affecting the output 
    static function test1() { 
     static::classname(); 
    } 
} 

class B extends A { 
} 

$v = new B(); 
B::test1(); 
$v->test1(); 

輸出:

BB 
+0

本例沒有輸出'AA'? – Dan 2011-02-26 06:15:17

+0

我的不好,更新了這個問題。你需要使用遲到的靜態綁定。 – xzyfer 2011-02-26 06:24:37

+1

如果你想在classname()中得到被調用的類而不在子中再次實現它,你可以將它從'echo__CLASS__;'改爲'echo get_called_class();'(像LSB一樣需要PHP> = 5.3.0) – 2011-02-26 06:29:27

2

關於你提到的第二個「瘋狂「的問題,請參閱Magic Methods。基本上,你需要實現這樣的:

class Foo 
{ 
    public function __call($name, $arguments) 
    { 
    // call the _$name function 
    } 

    public static function __callStatic($name, $arguments) 
    { 
    // call the _{$name}_static function 
    } 

    private function _bar() 
    { 
    } 

    private static function _bar_static() 
    { 
    } 
} 

$foo = new Foo(); 
$foo->bar(); 
Foo::bar(); 
+0

謝謝,非常好的答案! – Dan 2011-02-26 06:36:39

0

有可能添加靜態方法,這樣

class Foo { 
public static function __callStatic() { 
// ....  
} 
} 

// in Other file 

// Call the static method 
Foo-->__callStatic() 

,並調用它的其他文件(在PHP)?