How to create an object of class $ this from a 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 the way I am above?

Instead:

  $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 them 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 haven't tried them in a child class yet, but I think # 2 won't work there.

Also, this does not work:

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

The result is a parsing error: Unexpected '(' This should be done in two steps, as in 2.) above, or even better, as in 1.).

+4
source share
3 answers

Just use the static

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

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

+5
source

You can 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(); 
+1
source

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

At startup, you will get the following output.

Test 1 - Test

Test 2 - Test

Initiated Test - Test

0
source

Source: https://habr.com/ru/post/1411052/


All Articles