2011-02-26 19 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)?