如何从类中实例化$ this类的对象?PHP

But*_*kus 5 php oop

我有一个这样的课:

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

}
Run Code Online (Sandbox Code Playgroud)

我的问题是:我可以按照上面的方式使用$ this吗?

代替:

  $new_obj = new $this($a,$b);
Run Code Online (Sandbox Code Playgroud)

我可以写:

  $new_obj = new someClass($a,$b);
Run Code Online (Sandbox Code Playgroud)

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

更新解决方案:

这两个都在基类中工作:

1.)

  $new_obj = new static($a,$b);
Run Code Online (Sandbox Code Playgroud)

2.)

  $this_class = get_class();
  $new_obj = new $this_class($a,$b);
Run Code Online (Sandbox Code Playgroud)

我还没有在儿童班上试过它们,但我认为#2会在那里失败.

此外,这不起作用:

  $new_obj = new get_class()($a,$b);
Run Code Online (Sandbox Code Playgroud)

它导致一个解析错误:意外的'('必须分两步完成,如2.),或者更好,如1).

Phi*_*hil 5

简单,使用static关键字

public static function buildMeANewOne($a, $b) {
    return new static($a, $b);
}
Run Code Online (Sandbox Code Playgroud)

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