如何从类内部实例化$this类的对象?.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 - 测试

测试已启动 - 测试

最新更新