-
Singleton pattern saying "there should be no more than one instance of same class", is this something one should stick to when designing PHP OOP applications?
What are advantages / disadvantages?class myDOMDocument { private $DOMDocument = new DOMDocument(); private $HTML; public function __construct($html_str) { $this->HTML = $html_str; $this->processHTML(); } public function processHTML() { ... } } //instance 1 $page_three_obj = new myDOMDocument ($html_one); //instance 2 $page_three_obj = new myDOMDocument ($html_two); //instance 3 $page_three_obj = new myDOMDocument ($html_three);
-
Passing object to an object is good practice in OOP versus passing data between two objects as public method arguments?
What are advantages / disadvantages of both ways?
Passing object to an object
class one {
public $myProperty;
...
}
$One = new one();
class two {
private $Obj1;
public function __construct(One $Obj1) {
$this->$Obj1 = $Obj1;
}
public function doSomething() {
... $this->$Obj1->myProperty ...
}
}
$Two = new two($One);
$Two->doSomething();
vs passing data between two objects
class one {
public $myProperty;
...
}
$One = new one();
class two {
public function doSomething($inputArg) {
... $inputArg ...
}
}
$Two = new two();
$Two->doSomething($One->myProperty);
Best Answer
and definitely not "there should be no more than one instance of same class" (for each class of your application). The latter one makes seldom sense for any kind of real world OO application. There might be objects from which you need a dozen, thousands or millions of instances, or objects for which only one instance makes sense. It actually depends on the use case and what kind of abstraction you are modeling with your objects.
Independently from this, "Singleton" (as described above, not the misconception of it) is a pattern for which lots of developers nowadays think it is an anti-pattern, but the latter has nothing to do with your initial misunderstanding.