Owen
Owen

Reputation: 7607

PHP OOP - getting instance of object into another class

I want to get an instance of an existing object. How do I do this without having to pass the object as a parameter? This is what I'm doing now:

class clas1 {
    public $myArray;

    public function setArray($a){
        $this->myArray = $a;
    }
}

class clas2 {
    public $test;

    function __construct($obj) {
        $this->test = $obj;
    }
}

$c = new clas1;
$c->setArray(array('firstname'=>'Fred'));

$c2 = new clas2($c);

var_dump($c2);

The output of var_dump is:

object(clas2)[2]
  public 'test' => 
    object(clas1)[1]
      public 'myArray' => 
        array
          'firstname' => string 'Fred' (length=4)

I suppose I could have each object as a property of a parent object, but is are there any other suggestions?

Upvotes: 3

Views: 4227

Answers (2)

HappyDeveloper
HappyDeveloper

Reputation: 12805

Pulling objects by calling static methods (like in singleton) is a bad practice (or even an anti-pattern). Singleton and static classes feel natural for newcomers because they work the same way we learned in the procedural paradigm, but you should avoid them (only use static classes when they have no state)

You should totally pass the object as a parameter, to avoid introducing implicit dependencies, and do good OOP.

Read about Dependency Injection.

If object creation becomes complex or annoying, you can always use a Dependency Injection Container

Upvotes: 2

Alex Pliutau
Alex Pliutau

Reputation: 21947

You should use sigleton pattern:

class class1
{
    private static $_instance;
    public static function getInstance()
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new self;
        }
        return self::$_instance;
    }
    private function __construct() {}
    private function __clone() {}
}

class class2 {
    public function __construct()
    {
        $obj = class1::getInstance();
    }
}

$a = class1::getInstance();
$b = new class2();

Upvotes: 0

Related Questions