我有這樣一個類:
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;
}
}
我的問題是:我可以在我上面的方法使用$嗎?
相反的:
$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);
我還沒有嘗試過在小孩班上,但我認爲#2會在那裏失敗。
而且,這不起作用:
$new_obj = new get_class()($a,$b);
它導致解析錯誤:意外「(」 它必須在兩個步驟來完成,如2)以上,或更好,但在1)。
您的代碼缺少一個分號。 $ return_array [] = $ new_obj; – yehuda