在 PHP 中获取一个类的所有实例 [英] Get all instances of a class in PHP
问题描述
我想获取某个类的对象的所有实例.
I would like to get all the instances of an object of a certain class.
例如:
class Foo {
}
$a = new Foo();
$b = new Foo();
$instances = get_instances_of_class('Foo');
$instances
应该是 array($a, $b)
或 array($b, $a)
(顺序不很重要).
$instances
should be either array($a, $b)
or array($b, $a)
(order does not matter).
一个加号是如果函数将返回具有所请求类的超类的实例,尽管这不是必需的.
A plus is if the function would return instances which have a superclass of the requested class, though this isn't necessary.
我能想到的一种方法是使用一个静态类成员变量,它包含一个实例数组.在类的构造函数和析构函数中,我会从数组中添加或删除 $this
.如果我必须在许多类上这样做,这会相当麻烦且容易出错.
One method I can think of is using a static class member variable which holds an array of instances. In the class's constructor and destructor, I would add or remove $this
from the array. This is rather troublesome and error-prone if I have to do it on many classes.
推荐答案
如果您从 TrackableObject 类派生所有对象,则可以设置该类来处理此类事情(请确保您调用 parent::__construct()
和 parent::__destruct()
在子类中重载它们时.
If you derive all your objects from a TrackableObject class, this class could be set up to handle such things (just be sure you call parent::__construct()
and parent::__destruct()
when overloading those in subclasses.
class TrackableObject
{
protected static $_instances = array();
public function __construct()
{
self::$_instances[] = $this;
}
public function __destruct()
{
unset(self::$_instances[array_search($this, self::$_instances, true)]);
}
/**
* @param $includeSubclasses Optionally include subclasses in returned set
* @returns array array of objects
*/
public static function getInstances($includeSubclasses = false)
{
$return = array();
foreach(self::$_instances as $instance) {
if ($instance instanceof get_class($this)) {
if ($includeSubclasses || (get_class($instance) === get_class($this)) {
$return[] = $instance;
}
}
}
return $return;
}
}
这样做的主要问题是垃圾收集不会自动拾取任何对象(因为对它的引用仍然存在于 TrackableObject::$_instances
中),所以 __destruct()
需要手动调用以销毁所述对象.(循环引用垃圾回收是在 PHP 5.3 中添加的,可能会提供额外的垃圾回收机会)
The major issue with this is that no object would be automatically picked up by garbage collection (as a reference to it still exists within TrackableObject::$_instances
), so __destruct()
would need to be called manually to destroy said object. (Circular Reference Garbage Collection was added in PHP 5.3 and may present additional garbage collection opportunities)
这篇关于在 PHP 中获取一个类的所有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!