PHP overwrites object without it being used [edited]

69 views Asked by At

Alright, I was put on hold because it wasn't clear what I am asking, so let me rephrase. I have this variable:

$town->streets

I declare it like so:

$town->streets[$i] = new street;
$town->streets[$i] = (Object)newStreet();

Of course I do it inside a for loop. The newStreet() function generates a random number of houses for the street, each house has some attributes, such as type, tenants, is it a shop or library, what items there are inside if so, and so on. Right afterwards I echo the attributes of shop type houses to see if they are different.

As intended, every shop has different attributes. Now, right afterwards I have some code and after that I do the same echoing for houses again. However now each shop is the same as the last shop of the array, meaning that it somehow got overwritten inside some code. I am not accessing the houses, but am modifying other variables inside the streets. Yet I don't know why the houses and shops are getting overwritten.

The code does its task, meaning that cores and streets are distributed as I wanted to, so there are no actual errors, the objects' structure has never been a problem before, even though I have multiple objects structured like this. I am also aware that putting an object in a variable just creates a reference to it (or so I was told), but I still don't see why it is partially modified when I am not even accessing those parts at all.

some code is as follows:

$town->cores[0] = new core;
    $town->cores[0]->id = 0;

    for($i = 0;$i < $streetnum;$i++){
        if($town->streets[$i]->start == -1){
            $cid = round(mt_rand(0,count($town->cores)-1));
            $town->streets[$i]->start = $cid;
            if(count($town->cores) > 1 && round(mt_rand(0,10)) > 8){//PICK EXISTING CORE
                $ends = $town->cores;
                unset($ends[$cid]);
                $town->streets[$i]->end = $ends[array_rand($ends,1)]->id;

            }else{//NEW CORE
                $town->streets[$i]->end = count($town->cores);
                $town->cores[$town->streets[$i]->end] = new core;
                $town->cores[$town->streets[$i]->end]->id = $town->streets[$i]->end;

            }

        }

    }

    }
0

There are 0 answers