I recently had written some code to deal with instantiating a object, assigning a object and some data to the objects properties and then perform a call to a method in order to do something.
But when running the code in a loop, it failed to work and I couldn't understand why, my sample code is :-
Controller functionality :-
$arrayOfObjects = SomeClass::getItems();
foreach ($arrayOfObjects as $object) {
SomeOtherObject::getInstance($object, time())->run();
}
SomeOtherObject::getInstance() :-
public static function getInstance($object, $timestamp) {
if (!(self::$_instance instanceof self)) {
self::$_instance = new self($object, $timestamp);
}
return self::$_instance;
}
private function __contruct($object, $timestamp) {
$this->_theObjectPassed = $object;
$this->_theTimestampPassed = $timestamp;
}
What baffled me was that the run method on the SomeOtherObject wasn't doing what I expected. When I added debugging within the loop i.e. outputting a getName() method on the $object I got the same one for each item in the loop.
When changing the way I construct the object to the following (instead of getInstance()) it worked :-
$someOtherObject = new SomeOtherObject($object, time());
$someOtherObject->run();
I'm guessing it has something to do with the way the getInstance method works and how it is checking but wondered if anyone could explain it.
Thanks
Looks like you misunderstood static variables. A static variable will be created / initialized once per class and not once per object.
Your if statement will be true only the first time getInstance() is called , when $_instance hasn't been initialized. A reference to a new instance of SomeOtherObject will be assigned to it then.
On all following calls the if will return false and the existing $_instance will just being returned instead of creating a new one.
Remove the if statement from the getInstance() method:
public static function getInstance($object, $timestamp) {
return new self($object, $timestamp);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With