Something I haven't seen a lot of on Google search or anything is questions about PHPs max class handling at runtime.
Say I have a custom arrayaccess class that could house upto 8k objects of type "User".
Since the arrayaccess
class does not allow me to do:
$d[0]->username = "sam"
And set the class only for a residual object like I can in iterator when you do a foreach()
each loop brings out an object but the array itself has got no objects in, it just assigns a new populated object (allowing you to reuse the same spot in memory over and over) in each loop of the array. I can only set a object in the offsetGet()
method within the offset of the array within the arrayaccess
class. Due to this I would need to house anything upto 8K objects at any one point within this arrayaccess
class (maybe even 20k objects).
So each offset in my arrayaccess
class could be an object of say "User" and there could be upto 20k of them (8k at least).
My Question is: Would PHP be able to handle this amount of class instances? I mean this is a lot of classes and I am worried it could easily ruin my memory consumption.
Question is: Can you use it? It works fine for index arrays
http://sandbox.phpcode.eu/g/38fde.php
this works fine
You are talking about objects and not classes.
PHP has no problem dealing with a lot of objects, but if there is an issue just increase the
memory_limit
inphp.ini
.My motto is; if you're asking questions about limits, you're probably doing something wrong. Why do you need 8k instances of a class? Wouldn't a simple array suffice for this specific case? Are you building a list? If so, wouldn't it be beneficial to implement paging?
I use objects when I can and when they're called for. If you're using 8k of objects, you're probably doing something like reporting, where instantiating an object is not really suitable for, and is generally discouraged. If you want to do reporting, either use simple arrays (as you won't actually use the behaviour of the object), or leave the calculations to the database.
The amount of classes that you can instantiate (objects) is normally bound by the memory limit. So it depends how much memory is consumed by each object and the total number of objects.
So you actually need to test how much memory your objects will consume. I've put together a little test for demonstration purposes. That one shows that more of
439 000
instances of (small)stdClass
object instances are possible with a128m
memory limit:So to answer your question: You need to test how much memory your scenario actually consumes, this will show you how many object instances you can have. It's less the
arrayaccess
but more the actual number of objects instances and the data associated with them in total of your application.See as well: PHP: do arrays have a maximum size?