I want to create an object from inside the method of an object of the same class in PHP.
I have this simple code:
<?php class Animal { public $name = "cat"; public function test() { $this->name = "dog"; return new self; } } $animal = new Animal; $best = $animal->test(); echo $animal->name; echo '<br>'; echo $best->name; ?> The code works just fine with the new object getting assigned to the $best variable. However, I keep reading that self keyword is used in static context only (for static methods, properties, and constants).
Is what I'm doing correct or I should refer to the class name in another way other than self in this case?
staticitems - it also means it refers to the class itself.__CLASS__. Like this$class = __CLASS__; return new $class;but again I don't know is this more correct or all the ways are basically the same