Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP OOP - getting instance of object into another class

Tags:

oop

php

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?

like image 491
Owen Avatar asked Mar 21 '26 10:03

Owen


1 Answers

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

like image 97
HappyDeveloper Avatar answered Mar 23 '26 23:03

HappyDeveloper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!