【问题标题】:Creating a new instance of class being called rather than parent创建一个被调用的类的新实例而不是父类
【发布时间】:2012-11-23 16:12:54
【问题描述】:

当方法在父类中时,如何返回被调用类的实例。

例如。在下面的示例中,如果我调用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();
    }
}

【问题讨论】:

  • 您编写的代码应该给出致命错误。抽象类 (A) 无法实例化。

标签: php inheritance static


【解决方案1】:
$instance = new static;

您正在寻找Late Static Binding

【讨论】:

    【解决方案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;
    }
    

    【讨论】:

      【解决方案3】:

      你只需要:

      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 ;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-28
        • 1970-01-01
        • 2017-10-06
        • 2016-08-25
        • 2020-07-16
        • 2021-05-22
        • 2019-02-12
        相关资源
        最近更新 更多