2

メソッドが親クラスにある場合、呼び出されているクラスのインスタンスを返すにはどうすればよいですか。

例えば。B以下の例では、 if I callのインスタンスを返すにはどうすればよいB::foo();ですか?

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();
    }
}
4

3 に答える 3

21
$instance = new static;

Late Static Bindingを探しています。

于 2012-11-23T16:17:33.990 に答える
2

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;
}
于 2012-11-23T16:16:55.150 に答える
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 ;
    }
}
于 2012-11-23T16:19:12.063 に答える