列出某个类的所有对象 [英] Listing all objects of a certain class

查看:78
本文介绍了列出某个类的所有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我的问题如下;

Ok my problem is as follows;

我有一个用此构造函数描述宠物的类;

I have a class that describes a pet with this constructor;

public function __construct($name, $type, $age)

所以我要做的是制作一些宠物对象,然后我要打印该类所有对象的所有属性,以使其看起来像

So what I want to do is make a number of pet objects, then I want to print all the attributes of all the objects of this class so that it looks something like this

最好的解决方法是什么?我知道如何遍历对象的变量,但是我主要关心的是如何遍历特定类的所有对象.如果有人可以向我展示某些东西的代码示例,尤其是如果有一种方法可以不用数组的话,我会喜欢它的.

What is the best way of going about it? I know how to iterate through an object's variables, but my main concern is how to iterate through all objects of a certain class. I would love it if someone could show me a code example of something, particularly if there is a way to do it without the use of arrays.

感谢您的帮助!

推荐答案

通常,您希望能够以某种方式跟踪已创建的实例,可能在数组或某种包含类中.

Normally you would expect to have some way of tracking the instances you've created, maybe in an array or some kind of containing class.

但是为了便于讨论,您可以使用 get_defined_vars()检查当前作用域中的所有变量. ,以类似的方式递归搜索您找到的任何数组或对象:

But for the sake of argument, you could check all the variables in the current scope with get_defined_vars(), recursively searching any arrays or objects you find, with something like this:

function findInstancesOf($classname, $vars)
{
    foreach($vars as $name=>$var)
    {
        if (is_a($var, classname)) 
        {
             //dump it here
             echo "$name is a $classname<br>";

        }
        elseif(is_array($var))
        {
             //recursively search array     
             findInstancesOf($classname, $var);
        }
        elseif(is_object($var))
        {
             //recursively search object members
             $members=get_object_var($var);     
             findInstancesOf($classname, $members);
        }
    }
}

$vars = get_defined_vars();
findInstancesOf('MyPetClass', $vars);

这篇关于列出某个类的所有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆