I have a class in which I implement an array attribute. I want to set a couple of objects into that attribute. It will be done during the request flow many times, so it’s declared as static. And it’s not a singleton class.
Will the attribute in that class keep its earlier values when I’ll add something to this the second time?
(adding is done through a static method, if this changes anything)
The example:
/* file1.php */
Foo::add('value1');
include 'file2.php';
/* file2.php */
...
Foo::add('value2');
This is the definition of Foo:
class Foo {
public static $bar = [];
public static function add($value)
{
Foo::$bar[] = $value;
}
}
Is this a good practice? Is singleton better here? Is there any other way to deal with this?
Yes. The
include()andrequire()statements essentially dump the contents of the referenced file into the location of the statement. You can think of it all as one script.You can test your question yourself by adding
var_dump(Foo::bar);to the end of the script.Using the Singleton pattern is only really necessary if you only ever want the class instantiated/initialized once. If you will ever want to have additional instances within a script then you’ll want to leave it as a normal class and start working out how to do what you want. ie: Passing by reference.