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?