To implement array-style appending (e.g. "$object[] = 'foo';") in your own class implementing the ArrayAccess _interface_, all you need do is check if the key passed to your implementation of offsetSet() is NULL. Something like the following.
<?php
class MyArrayObject implements ArrayAccess {
/**
* @var array
*/
private $aValue;
// ...
/**
* @see ArrayAccess::offsetSet()
*/
public function offsetSet ($p_key, $p_value) {
if (is_null($p_key)) {
$this->aValue[] = $p_value;
}
else {
$this->aValue[$p_key] = $p_value;
}
}
// ...
}
?>
The ArrayObject class
Introduction
This class allows objects to work as arrays.
Class synopsis
ArrayObject
/* Constants */
/* Methods */
}Predefined Constants
ArrayObject Flags
- ArrayObject::STD_PROP_LIST
-
Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.).
- ArrayObject::ARRAY_AS_PROPS
-
Entries can be accessed as properties (read and write).
Table of Contents
- ArrayObject::append — Appends the value
- ArrayObject::asort — Sort the entries by value
- ArrayObject::__construct — Construct a new array object
- ArrayObject::count — Get the number of public properties in the ArrayObject
- ArrayObject::exchangeArray — Exchange the array for another one.
- ArrayObject::getArrayCopy — Creates a copy of the ArrayObject.
- ArrayObject::getFlags — Gets the behavior flags.
- ArrayObject::getIterator — Create a new iterator from an ArrayObject instance
- ArrayObject::getIteratorClass — Gets the iterator classname for the ArrayObject.
- ArrayObject::ksort — Sort the entries by key
- ArrayObject::natcasesort — Sort an array using a case insensitive "natural order" algorithm
- ArrayObject::natsort — Sort entries using a "natural order" algorithm
- ArrayObject::offsetExists — Returns whether the requested index exists
- ArrayObject::offsetGet — Returns the value at the specified index
- ArrayObject::offsetSet — Sets the value at the specified index to newval
- ArrayObject::offsetUnset — Unsets the value at the specified index
- ArrayObject::serialize — Serialize an ArrayObject
- ArrayObject::setFlags — Sets the behavior flags.
- ArrayObject::setIteratorClass — Sets the iterator classname for the ArrayObject.
- ArrayObject::uasort — Sort the entries with a user-defined comparison function and maintain key association
- ArrayObject::uksort — Sort the entries by keys using a user-defined comparison function
- ArrayObject::unserialize — Unserialize an ArrayObject
ArrayObject
danbettles at yahoo dot co dot uk
23-Aug-2009 03:56
23-Aug-2009 03:56
skrebbel at gmail dot com
18-Apr-2009 10:25
18-Apr-2009 10:25
According to my benchmarks, doing foreach() on an ArrayObject is significantly slower than doing so on a vanilla array(). However, inserting keys and retrieving them is almost the same speed.
So, if performance is important, consider not using ArrayObject or descendant classes when you're iterating over its values a lot.
These are my timing results, using PEAR::Benchmark:
ArrayObject fill 0.01441502571106
ArrayObject read_key 0.018320083618164
ArrayObject read_foreach 2.1559031009674
array() fill 0.012364864349365
array() read_key 0.013092041015625
array() read_foreach 0.011217832565308
In all cases, 'fill()' inserts 10000 numbers at string keys, 'read_key()' reads all of those values by referencing the keys, and 'read_foreach()' does the same by walking through the array(object) with foreach().
As you can see, filling or reading from an ArrayObject by key is only 10% to 15% slower, but doing a foreach() is 200 times as costly. I am not sure what the cause of this may be.
nonproffessional at clockworkgeek dot com
09-Mar-2009 07:04
09-Mar-2009 07:04
To get a primitive array type back from an ArrayObject you can use the member function exchangeArray() or more simply just cast it:
<?php
$object = new ArrayObject();
$object[] = "Hello World!";
// $object is now an ArrayObject with one value appended.
$array = (array) $object;
// $array is now a simple array with the single value "Hello World!".
?>
deminy at deminy dot net
02-Jan-2009 09:31
02-Jan-2009 09:31
Generally variable $this can't be used as an array within an object context. For example, following code piece would cause a fatal error:
<?php
class TestThis {
public function __set($name, $val) {
$this[$name] = $val;
}
public function __get($name) {
return $this[$name];
}
}
$obj = new TestThis();
$obj->a = 'aaa';
echo $obj->a . "\n";
?>
But things are different when $this is used in an ArrayObject object. e.g., following code piece are valid:
<?php
class TestArrayObject extends ArrayObject {
public function __set($name, $val) {
$this[$name] = $val;
}
public function __get($name) {
return $this[$name];
}
}
$obj = new TestArrayObject();
$obj->a = 'aaa';
echo $obj->a . "\n";
?>
Venelin Vulkov
05-Nov-2008 09:09
05-Nov-2008 09:09
Simple example of usage :
<?php
$array = array('Buck','Jerry','Tomas');
$arrayObject = new ArrayObject($array);
// Add new element
$arrayObject->append('Tweety');
// We are getting the iterator of the object
$iterator = $arrayObject->getIterator();
// Simple while loop
while ($iterator->valid()) {
echo $iterator->current() . "\n";
$iterator->next();
}
/* Outputs */
Buck
Jerry
Tomas
Tweety
?>
Note that not all the public methods of this class are documented here .
( Which includes a lot sorting methods ) .
Regards
tony dot fraser at gmail dot com
09-Oct-2008 03:30
09-Oct-2008 03:30
The code above will pretty much work as it is, though I have since added in some features.
Further notes:
1. Be very aware of this bug until 5.3 becomes stable.
http://bugs.php.net/bug.php?id=41528
Basically, we wrote this collection to be a java-like object cache stored in session (instead of hitting the soap server or a DB all the time) to load objects in $_SESSION['cache'] But, this particular bug will prevent the object from working in the second page. The variable is there, but there's nothing in it.
The easy work around is to upgrade PHP to 5.3, and it works like a charm, but at the moment 5.3 happens to be in alpha mode.
2. You cannot have a PDO object in as a member variable of a class stored in the ArrayObject if you want it to pass through sessions. You can store it if it's not going into a session, but if you want to cache like we're tying to do, make SURE you $_dbHandle="" wherever you need to.
3. My earlier post was just proof of concept. We have it working now so UserCollection extends GenericCollectionAbstract. and GenericCollectionAbstract implements the GenericCollectionInterface. GenericCollectionObject is the object stored in the GenericCollection's $arrayObject data, and is basically just a two property object that holds the ID of the object, and the object itself.
When all is said and done this works like a charm.
page 1 ->
$_SESSION['u'] = new UserCollection();
$_SESSION['u']->getObject(1, $dbWW);
page-2->
echo $_SESSION['u']->getObject(2, $dbWW)->getProperty('email');
And of course, getProperty() is from my user class.
my UserCollecton->getObject overwrite method is as follows:
<?php
public function getObject($_id, $_dbHandle){
//error_log('trying to get object');
if (parent::objectExists($_id)){
return parent::getObject($_id, $_dbHandle);
error_log('returning object');
}
else{
//error_log('collecting new user');
$_tempUser = new User();
if ($_tempUser->populateByID($_id, $_dbHandle)){
parent::addObject($_id, $_tempUser);
if (parent::objectExists($_id)) {
$_return = parent::getObject($_id);
}
else $_return = "";
}
else {
$_return = "";
}
$this->dbHandle=""; //This has to be done, otherwise it's stored in the object as a private var
//and it will break the object if it resides in a session.
return $_return;
}
?>
Shoot me an email if you have any questions.
enjoy.!
tony at tonyandcarol dot com
08-Oct-2008 02:49
08-Oct-2008 02:49
My need was to create a java-like collection where I could store objects by their DB primary keys while having the standard stack capabilities of adding, retrieving, and removing objects from collection. ArrayObject didn't quite do what I need it to do so I extended it a little.
<?php
class GenericCollection extends ArrayObject{
private $data;
function __construct(){
$this->data = new ArrayObject();
}
function addObject($_id, $_object){
$_thisItem = new CollectionObject($_id, $_object);
$this->data->offSetSet($_id, $_thisItem);
}
function deleteObject($_id){
$this->data->offsetUnset($_id);
}
function getObject($_id){
$_thisObject = $this->data->offSetGet($_id);
return $_thisObject->getObject();
}
function printCollection() {
print_r($this->data);
}
}
class CollectionObject {
private $id;
private $object;
function __construct($_id, $_object){
$this->id = $_id;
$this->object = $_object;
}
function getObject(){
return $this->object;
}
function printObject() {
print_r($this);
}
}
?>
Call it like so:
<?php
$u1 = new User/Data/Object (); //whatever, just an object.
$myCollection = new GenericCollection();
$myCollection->addObject(1, $u1);
print_r($myCollection->getObject(1));
?>
Now you have a simple and functional collection framework. Add methods in for specific types of sorting, we just didn't need anything other than primary key access. And you can add introspection into the collection object if you need to track what kind of an object it is.
tony@tonyandcarol.com
dave at csixty4 dot com
05-Sep-2008 03:28
05-Sep-2008 03:28
If you want to use array functions on an ArrayObject, why not use iterator_to_array() to get a standard PHP array? Do your operations on that array, then instantiate a new ArrayObject, passing it the array.
This might be a little slow on large ArrayObjects, but you'd have access to all of the array functions.
Anonymous
10-Aug-2008 01:17
10-Aug-2008 01:17
Too bad the Array functions [1] are not available on this object… otherwise I would be using it all the time.
[1] http://nl.php.net/manual/en/ref.array.php
