我有一个这样的课:

class someClass {

  public static function getBy($method,$value) {
    // returns collection of objects of this class based on search criteria
    $return_array = array();
    $sql = // get some data "WHERE `$method` = '$value'
    $result = mysql_query($sql);
    while($row = mysql_fetch_assoc($result)) {
      $new_obj = new $this($a,$b);
      $return_array[] = $new_obj;
    }
    return $return_array;
  }

}

我的问题是:我可以像上面一样使用$ this吗?

代替:
  $new_obj = new $this($a,$b);

我可以写:
  $new_obj = new someClass($a,$b);

但是,当我扩展该类时,我将不得不重写该方法。如果第一个选项有效,则无需这样做。

解决方案更新:

这两个都在基类中起作用:

1.)
  $new_obj = new static($a,$b);

2.)
  $this_class = get_class();
  $new_obj = new $this_class($a,$b);

我还没有在 child 类尝试过它们,但是我认为#2在那里会失败。

另外,这不起作用:
  $new_obj = new get_class()($a,$b);

它导致解析错误:意外的'('
必须按照上述2.)中的两个步骤完成,或者最好按照1.)中的步骤进行。

最佳答案

简单,使用static关键字

public static function buildMeANewOne($a, $b) {
    return new static($a, $b);
}

参见http://php.net/manual/en/language.oop5.late-static-bindings.php

关于php - 如何从类中实例化$ this类的对象?的PHP,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10476908/

10-09 06:47
查看更多