473,795 Members | 3,441 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

List all instances of a class?

I am a newcomer to PHP and am writing a script which dynamically creates
instances of a class with names like $object1, $object2, etc.. I now
want my script to be able to list all of the objects which are instances
of a specific class -- but I haven't been able to find any code which
does this in the online PHP references I've consulted. Given that the
names of the objects are predictable, it would be possible for me to
write some code which looped sequentially through the object names
$object1, $object2, etc., until it reached an object name which didn't
exist. However, I was expecting there to be a tidier, easier way of
doing the same thing with a command that says simply "List all instances
of class X."

Could you please tell me how to do this, or why it is not possible?
Jul 17 '05 #1
5 5775
L Robbins said the following on 05/06/2005 12:06:
I am a newcomer to PHP and am writing a script which dynamically creates
instances of a class with names like $object1, $object2, etc.. I now
want my script to be able to list all of the objects which are instances
of a specific class -- but I haven't been able to find any code which
does this in the online PHP references I've consulted. Given that the
names of the objects are predictable, it would be possible for me to
write some code which looped sequentially through the object names
$object1, $object2, etc., until it reached an object name which didn't
exist. However, I was expecting there to be a tidier, easier way of
doing the same thing with a command that says simply "List all instances
of class X."

Could you please tell me how to do this, or why it is not possible?


If you've got a load of sequentially numbered variables like $object1,
$object2, $object3 and you want to do things like loop through them, it
makes far more sense to use an array than discrete variables, i.e.
$object[0], $object[1], $object[2] (numbering usually starts from 0). Do
that and there's a whole host of PHP functions you can use that are
designed to manipulate arrays (see
http://www.php.net/manual/ref.array.php). This includes count(), which
tells you how many things there are in the array.

If you're not familiar with arrays, see
http://www.php.net/manual/language.types.array.php

--
Oli
Jul 17 '05 #2
L Robbins wrote:
Given that the names of the objects are predictable, it
would be possible for me to write some code which looped sequentially
through the object names $object1, $object2, etc., until it reached
an object name which didn't exist. However, I was expecting there to
be a tidier, easier way of doing the same thing with a command that
says simply "List all instances of class X."

Could you please tell me how to do this, or why it is not possible?


There is no function that returns all the instances of a class. If you want
to keep track of them, you could store them in an array or loop through the
$GLOBALS array and test each key with is_object() and instanceof (or is_a()
when not using PHP5).

When using PHP5, you could also keep track of all created instances as
follows:

<?php

class Foo {
private static $instance_count = 0;
public static function getInstanceCoun t() {
return self::$instance _count;
}

function __construct() {
self::$instance _count++;
}

function __destruct() {
self::$instance _count--;
}
}

$foo = new Foo;
print Foo::getInstanc eCount(); // 1

unset($foo);
print Foo::getInstanc eCount(); // 0

?>
JW

Jul 17 '05 #3
Thanks very much, Janwillem and Oli. In my neophyte's enthusiasm for
object-oriented PHP, I was trying to instantiate objects wherever I saw
the vaguest possibility for them. I have now reworked my code with a
wiser, more jaded eye (though I still think it would be nice if there
were an in-built way to list all instances of a class).
Jul 17 '05 #4
"L Robbins" <us**@domain.in valid> wrote in message
news:d7******** **@news.freedom 2surf.net...
Thanks very much, Janwillem and Oli. In my neophyte's enthusiasm for
object-oriented PHP, I was trying to instantiate objects wherever I saw
the vaguest possibility for them. I have now reworked my code with a
wiser, more jaded eye (though I still think it would be nice if there were
an in-built way to list all instances of a class).


Do other OO languages provide this facility? If not, then why do you expect
PHP to?

--
Tony Marston

http://www.tonymarston.net

Jul 17 '05 #5
L Robbins wrote:
I am a newcomer to PHP and am writing a script which dynamically creates
instances of a class with names like $object1, $object2, etc.. I now
want my script to be able to list all of the objects which are instances
of a specific class

<snip>

http://www.php.net/get_defined_vars

--
<?php echo 'Just another PHP saint'; ?>
Email: rrjanbiah-at-Y!com Blog: http://rajeshanbiah.blogspot.com

Jul 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1823
by: Crawley | last post by:
Im trying to create a list of lists and for some reason its not working: class Tile: _next = { 'n':None, 'ne':None, 'e':None, 'se':None, 's':None, 'sw':None, 'w':None, 'nw':None } def blankGridCanvas( maxx, maxy ): grid = for y in xrange( 0, maxy ):
2
1972
by: John Wohlbier | last post by:
Hi, I have a basic programming question regarding classes in python. I want to have a list of "primaryClass" instances, and in each instance of primaryClass I would like a list of "subClass" instances. When each primaryClass instance is created I want to put one instance of subClass into the "sClasses" list (see code). The attached code is what I came up with, but it doesn't do what I want. For some reason the "sClasses" list in each...
1
2090
by: NickB | last post by:
Please could someone tell me what is wrong. Ther error is: An unhandled exception of type 'System.NullReferenceException' occurred in microsoft.visualbasic.dll Additional information: Object variable or With block variable not set. I am trying to print the contents of a list box on another form. This is the sub, and the highlighted line is where it is falling over.
5
5444
by: majm | last post by:
I'm trying to implement strongly typed lists in the 2.0 framework. I'm using VS2005 beta 2. So far, System.Collections.Generic.List appears to be the ideal solution. However, the generic.List.IndexOf function doesn't appear to be invoking the contained class' CompareTo method. My understanding is that it should. The contained class (IssStruct) implements the IComparable and IComparable<T> interfaces. However, the List.Sort function...
90
10826
by: Christoph Zwerschke | last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in future Python versions and let dict.keys() and dict.values() both return sets instead of lists. If d is a dict, code like: for x in d.keys():
4
2821
by: Cedric Rogers | last post by:
I wasn't sure if I could do this. I believe I am stretching the capability of what generics can do for me but here goes. I have a generic delegate defined as public delegate bool RuleDelegate<T>(T item); In my class my goal is to use a generic list collection to contain my generic delegates. This will allow me to pass this List to another library and call this list of functions. This could provide a new way to build rule base...
3
2060
by: manstey | last post by:
how do I detect a change in a list of class instances? from copy import deepcopy class CaListOfObj(list): """ subclass of list """ def __init__(self, *args, **kwargs): list.__init__(self, *args, **kwargs) class CaClass(object):
8
12203
by: =?Utf-8?B?UGV0ZXI=?= | last post by:
I'm trying to get a list of SQL Server Instances thru a VB.NET application. I have tried GetDataSource and SMO. I have also tried using ListSQLSvr.exe from http://www.sqldev.net/misc/ListSQLSvr.htm I run all of them on a Windows XP Professional 64bit machine which has 2 instances: mymachine\SQLExpress (Express Edition) and MSSQLSERVER (Developer Edition (64bit)) SQL Browser Service: not running
6
1300
by: David C | last post by:
In my business layer, I have Person, and Patient which derives from Person. //base class for all single classes public class BaseItem{} public class Person:BaseItem{} public class Patient:Persons{}
0
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9519
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10214
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10164
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10001
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9042
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.