2012-05-07 64 views
4

我有這樣一個類:

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)。

+0

您的代碼缺少一個分號。 $ return_array [] = $ new_obj; – yehuda

回答

5

簡單,使用static關鍵字

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

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

+0

「return new self($ a, $ b)條;」 ? –

+1

@Buttle Butkus:'self'將不起作用,因爲它會引用定義在類中的類靜態方法。請參閱Phil給出的更多詳細信息鏈接 – zerkms

+0

我認爲使用「get_class()」,正如Bryan Moyles所建議的將遭受同樣的問題,對吧? –

0

使用try get_class(),這樣,即使類是繼承

<? 
class Test { 
    public function getName() { 
     return get_class() . "\n"; 
    } 

    public function initiateClass() { 
     $class_name = get_class(); 

     return new $class_name(); 
    } 
} 

class Test2 extends Test {} 

$test = new Test(); 

echo "Test 1 - " . $test->getName(); 

$test2 = new Test2(); 

echo "Test 2 - " . $test2->getName(); 

$test_initiated = $test2->initiateClass(); 

echo "Test Initiated - " . $test_initiated->getName(); 

運行時,你會得到下面的輸出。

測試1 - 測試

測試2 - 測試

測試啓動 - 測試

1

您可以使用ReflectionClass::newInstance

http://ideone.com/THf45

class A 
{ 
    private $_a; 
    private $_b; 

    public function __construct($a = null, $b = null) 
    { 
     $this->_a = $a; 
     $this->_b = $b; 

     echo 'Constructed A instance with args: ' . $a . ', ' . $b . "\n"; 
    } 

    public function construct_from_this() 
    { 
     $ref = new ReflectionClass($this); 
     return $ref->newInstance('a_value', 'b_value'); 
    } 
} 

$foo = new A(); 
$result = $foo->construct_from_this(); 
+0

不會在靜態方法中工作 – Phil

+0

@Phil:哦,上帝​​,不夠細心:-S對我而言'$ this'總是意味着非靜態方法:-S – zerkms

相關問題