user3380172
user3380172

Reputation: 37

Create an instance of an object inside a method

I read a book on OOP PHP, can not understand what the author means:

class Registry {
    /**
    * Array of objects
    */
    private $objects;

   public function createAndStoreObject($object, $key) {
       require_once($object.'.class.php');
       $this->objects[$key] = new $object($this);
   }
}

1) $this->objects[$key] - We saving a private class array value. 2) new $object($this) - I do not understand where we take the object $object (if this array) and what is meant in the sense of $this?

Upvotes: 0

Views: 81

Answers (3)

Danijel
Danijel

Reputation: 12719

It is example of Registry Design Pattern, which creates objects similar as the Factory Design Pattern. In this pattern, a class simply creates the object you want to use without necessarily knowing what kind of object it creates. In your example createAndStoreObject function creates a new instance of a class using a variable class name.

If, for example, $object = 'Foo', then is the same as:

   require_once('Foo'.'.class.php');
   $this->objects[$key] = new Foo($this);

The meaning of $this passed to the constructor is that all objects created can have access to the Registry object

Upvotes: 0

andrew hutchings
andrew hutchings

Reputation: 366

$this refers to the current object within scope so in your case the Registry class so you could call to the $object variable within the scope of you class by using $this->objects

Upvotes: 0

deceze
deceze

Reputation: 522597

$class = 'Foo';
$foo   = new $class;

is the same as

$foo = new Foo;

That explains what new $object does. And while it's instantiating a new instance of whatever $object is, it is passing $this to the object's constructor. I.e. it's passing a reference to the Registry object to the object that is being constructed.

Upvotes: 2

Related Questions