2013-08-01 24 views
1

我有两类:自::()方法调用使用父类的方法,而不是所谓的

class JController{ 
    public static function getInstance() 
    { 
     //some source, not important... 
     self::createFile();// 
    } 

    public static function createFile() 
    { 
     // this is base class method 
    } 
} 

class CustomController extends JController{ 

    public static function createFile() 
    { 
     // this is overriden class method 
    } 
} 

,我试图调用派生类的静态方法,它调用的父母方法和未覆盖。它预期的行为?

这就是我尝试使用它:

$controllerInstance = CustomController::getInstance(); 

我的问题是:在CustomController :: CREATEFILE为什么不CustomController ::的getInstance()调用()?

+0

可能重复http://stackoverflow.com/questions/13174343/overriding-static-methods-in -php) – Neal

+0

是的,它是一个重复的,没有找到它.. – insanebits

回答

6

这是预期的行为。在php 5.3之前,静态方法只会调用层次结构中第一个定义的方法。 5.3+具有late static binding支持,并且可以直接在子类上使用该方法。要做到这一点,你需要使用static关键字,而不是self

public static function getInstance() 
    { 
     //some source, not important... 
     static::createFile();// 
    } 
的[在PHP重写静态方法(
+0

感谢您的答案,但也许有其他方式呢?因为我最重要的课程是Joomla's,顺便说一下你的答案是第一个,我会在几分钟内接受 – insanebits

+0

不是我没有修改核心课程就能想到的。这就是说取决于createFile的逻辑,并且确切地说你想要的最终结果可能是另一种方式。 – prodigitalson

+0

我只需要调用我的静态方法而不是基类中的一个,所以我已经复制了该方法的源代码,并将'self'改为'static',它的工作方式就像一个魅力:) – insanebits