简体   繁体   中英

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

I have a class like this:

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

}

My question is: can I use $this in the way I have above?

Instead of:

  $new_obj = new $this($a,$b);

I could write:

  $new_obj = new someClass($a,$b);

But then when I extend the class, I will have to override the method. If the first option works, I won't have to.

UPDATE on solutions:

Both of these work in the base class:

1.)

  $new_obj = new static($a,$b);

2.)

  $this_class = get_class();
  $new_obj = new $this_class($a,$b);

I have not tried them in a child class yet, but I think #2 will fail there.

Also, this does not work:

  $new_obj = new get_class()($a,$b);

It results in a parse error: Unexpected '(' It must be done in two steps, as in 2.) above, or better yet as in 1.).

Easy, use the static keyword

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

See http://php.net/manual/en/language.oop5.late-static-bindings.php .

You may use 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();

Try using get_class(), this works even when the class is inherited

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

When running, you'll get the following output.

Test 1 - Test

Test 2 - Test

Test Initiated - Test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM