On 6 aug, 19:16, BiraRai <bira...@gmail.comwrote:
is it possible to add new variable to a array object at run time?
the following code does not work.
$iterator->current()->['newProperty'] = 1234;
Here is some code where I did some assumptions about how your example
works and an explanation. Basically, you can change the return value
of current() if it is a reference, which is the case in objects, but
not when it is any other type.
Besides, you are trying to access the return value of current() as an
object in one line and as an array in the next. This is not possible.
You are probably better off not using an iterator, but an array and a
foreach or for loop, if you want to change arrays.
<?php
class MyIterator {
var $index = 0;
var $contents = array();
function current() {
return $this->contents[$this->index];
}
function next() {
$this->index++;
}
function valid() {
return $this->index < count($this->contents);
}
}
class Properties {
var $iterator = null;
function getMyIterator() {
return $this->iterator;
}
}
function bandingCalculator($properties){
$iterator = $properties->getMyIterator();
while ( $iterator->valid() ){
if (is_object($iterator->current())) {
/* This works. It adds BAND_ASSESSMENT to the current object. The
current() function actually returns a reference to an object, that you
can use to access the object. */
$iterator->current()->BAND_ASSESSMENT = 666;
/* This does not work. It gives a parse error. Besides that,
current() returns an object and you try to access it as an array. */
// $iterator->current()->['newProperty'] = 1233;
}
if (is_array($iterator->current())) {
/* An array is not an object. Instead of returning a reference,
current() now returns a copy of the array. You can change the copy,
but that will get you nowhere. You can change current() to
specifically return a reference, but that would not be the ideal way
to do this. */
$current = $iterator->current();
$current['newProperty'] = 1234;
}
print_r($iterator->current());
$iterator->next();
}
}
$object = new stdClass();
$object->TAX_CODE = "GF";
$array = array(1, 2);
$iterator = new MyIterator();
$iterator->contents = array($object, $array);
$properties = new Properties();
$properties->iterator = $iterator;
bandingCalculator($properties);
?>