Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

oop

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

like image 539
Buttle Butkus Avatar asked May 07 '12 05:05

Buttle Butkus


2 Answers

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.

like image 140
Phil Avatar answered Nov 15 '22 00:11

Phil


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();
like image 31
zerkms Avatar answered Nov 14 '22 22:11

zerkms