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?

5
  • 1
    stackoverflow.com/questions/5197300/new-self-vs-new-static may be worth a read. Commented Sep 28, 2019 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 Commented Sep 28, 2019 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. Commented Sep 28, 2019 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 Commented Sep 28, 2019 at 10:27
  • Another reference may be stackoverflow.com/questions/24653108/… Commented Sep 28, 2019 at 10:30

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.