0

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?

Michael Samuel
  • 3,820
  • 12
  • 45
  • 85
  • 1
    https://stackoverflow.com/questions/5197300/new-self-vs-new-static may be worth a read. – Nigel Ren Sep 28 '19 at 10:10
  • @NigelRen this question addresses mainly the late static binding issue, totally different story. I'm talking here about regular methods and properties not static ones – Michael Samuel Sep 28 '19 at 10:13
  • The reason I didn't close it as a dupe was that I know the question is different, but there is information in there which may help - i.e. *self refers to the same class in which the new keyword is actually written*, so although in most contexts - this would refer to `static` items - it also means it refers to the class itself. – Nigel Ren Sep 28 '19 at 10:15
  • @NigelRen I found there is another way to do the same using the magic constant `__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 – Michael Samuel Sep 28 '19 at 10:27
  • Another reference may be https://stackoverflow.com/questions/24653108/right-way-to-instantiate-class-in-php – Nigel Ren Sep 28 '19 at 10:30

0 Answers0