I have the following classes.
The problem is that $_instance is getting shared amongst both AuthFactory and UserFactory.
class Factory {
protected static $_instance;
/*...*/
}
class AuthFactory extends Factory {
protected static $_instance;
/*...*/
}
class UserFactory extends Factory {
protected static $_instance;
/*...*/
}
How can I avoid the object in AuthFactory::$_instance being the same object as UserFactory::$_instance?
The whole reason for this is that I can set the structure in Factory, and extend if for each actual factory that I want to use.
My experience is as follows:
If you declare a property static then its value will be shared between the class it’s defined in and all subclasses.
The exception is if you redeclare the same property in the subclasses. In that case, each subclass will have its own value. This means you need to remember to redeclare the property.
However, due to issues related to late static binding, if you use self::$variable to access the property, then the value will be taken from the superclass (if the accessing method was defined in the superclass. I’m not sure what happens if the accessing method was defined in the subclass).
If you use static::$variable instead, then this shouldn’t be an issue, but I’ve not tested that extensively under all conditions.
Are you using self::$_instance or static::$_instance to access the property in question? If it’s the former then try changing to the latter.
I suspect, however it might be better just to make the property non-static, depending on what it’s meant to be used for.