簡體   English   中英

如何從類中實例化$ this類的對象? 的PHP

[英]How to instantiate object of $this class from within the class? PHP

我有一個這樣的課:

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

我還沒有在兒童班上嘗試過它們,但是我認為#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

您可以使用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();

嘗試使用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-測試

測試啟動-測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM