5

我有这样的课:

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

它会导致解析错误:Unexpected '(' 它必须分两步完成,如上面的 2.),或者更好,如 1.)。

4

3 回答 3

5

简单,使用static关键字

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

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

于 2012-05-07T05:26:48.187 回答
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();
于 2012-05-07T05:12:05.937 回答
0

尝试使用 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 - 测试

测试启动 - 测试

于 2012-05-07T05:07:18.937 回答