global arrays and references
| From: | patrick dooley | Date: | Wed, 16 Aug 2000 14:28:30 +0000 |
| Subject: | global arrays and references | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-12012@lists.php.net to get a copy of this message | ||
Hi,
I posted this over the weekend but got no takers, so
this may look familiar.
I'm trying to get PHP to maintain global a pool of
objects that represent rows in a database. I have a
global 2D array. The first dimension is the className
and the second is just an index for each object of
that class. Anyway, when I put a new reference into
the list, the previous values all get reset to those
of the last included object. I've messed around with
trying to unset the references, but I haven't had any
luck. I've included a chunk of ugly code that
reproduces this. Oh, I'm using PHP4.0.1pl2 on Linux
with Apache & MySQL.
Thanks so much
patrick
$obj0 = &myNew("Obj", 0);
inspectObjects();
$obj1 = &myNew("Obj", 1);
inspectObjects();
/*
//OUTPUTS:
Obj
key: 0
Obj
key: 1
key: 1
*/
<?php
// global to track all instances of classes
$objects;
function &myNew($className, $key) {
global $objects;
$set = &$objects[$className];
if (is_array($set)) {
for ($i = 0, $n = sizeof($set); $i < $n; $i++) {
$obj = &$set[$i];
if ($obj->key == $key) {
return $obj;
}
}
} else {
$set = array();
$objects[$className] = &$set;
}
// didn't find it, so create it
$obj = null;
$constructorStr = "\$obj = new " . $className .
"(\$className, \$key);";
eval($constructorStr);
$set[sizeof($set)] = &$obj;
return $obj;
}
function inspectObjects() {
global $objects;
if (!is_array($objects)) {
print("<br>No objects recorded!");
return;
}
foreach($objects as $class => $objs) {
if (is_array($objs)) {
print("<br>" . $class);
foreach($objs as $obj) {
print("<br> key: " . $obj->key);
}
}
}
}
class Obj {
var $key;
var $className;
var $data;
function Obj($className, $key) {
$this->className = $className;
$this->key = $key;
$this->data = array();
}
}
?>
__________________________________________________
Do You Yahoo!?
Send instant messages & get email alerts with Yahoo! Messenger.
http://im.yahoo.com/