2012-11-23 47 views
1

当方法位于父类中时,如何返回被调用类的实例。创建被调用类的新实例而不是父类

例如,在下面的示例中,如果我拨打B::foo();,如何返回B的实例?

abstract class A 
{ 
    public static function foo() 
    { 
     $instance = new A(); // I want this to return a new instance of child class. 
      ... Do things with instance ... 
     return $instance; 
    } 
} 

class B extends A 
{ 
} 

class C extends A 
{ 
} 

B::foo(); // Return an instance of B, not of the parent class. 
C::foo(); // Return an instance of C, not of the parent class. 

我知道我能做到这样的事情,但有一个更合适的方法:

abstract class A 
{ 
    abstract static function getInstance(); 

    public static function foo() 
    { 
     $instance = $this->getInstance(); // I want this to return a new instance of child class. 
      ... Do things with instance ... 
     return $instance; 
    } 
} 

class B extends A 
{ 
    public static function getInstance() { 
     return new B(); 
    } 
} 

class C extends A 
{ 
    public static function getInstance() { 
     return new C(); 
    } 
} 
+0

你所写的代码应该给一个致命的错误。抽象类(A)不能被实例化。 –

+0

它是一个例子。 – Adam

回答

16
$instance = new static; 

您正在寻找Late Static Binding

+0

请参阅http://3v4l.org/PMs8L进行测试。 – deceze

+0

完美的作品,谢谢你接受我的答案! – Adam

1

http://www.php.net/manual/en/function.get-called-class.php

<?php 

class foo { 
    static public function test() { 
     var_dump(get_called_class()); 
    } 
} 

class bar extends foo { 
} 

foo::test(); 
bar::test(); 

?> 

结果

string(3) "foo" 
string(3) "bar" 

所以你的函数将会是:

public static function foo() 
{ 
    $className = get_called_class(); 
    $instance = new $className(); 
    return $instance; 
} 
0

所有你需要的是:

abstract class A { 
    public static function foo() { 
     $instance = new static(); 
     return $instance ; 
    } 
} 

或者

abstract class A { 
    public static function foo() { 
     $name = get_called_class() ; 
     $instance = new $name; 
     return $instance ; 
    } 
} 
相关问题