D
D
Dmitry Batulin2016-05-18 15:09:21
PHP
Dmitry Batulin, 2016-05-18 15:09:21

Subtleties of OOP in PHP. Why is data overwritten?

Good afternoon!
Faced strange PHP behavior. Well, or with their incomplete competence in this matter.
Ask for help from knowledgeable people.
Thanks in advance.
The essence of the situation.
There is a figurative static class Items
it has 2 static functions
Items::preload() - forms an array of items and writes to the private property of the class
Items::getItems() - returns a list of items generated by the first function
Now, what does not work as I would like.

Items::preload();
$list = array(
    'action1' => 'addOne',
    'action2' => 'addTwo'
);
foreach( $list as $key => $action ){
    $itemList = Items::getItems();
    foreach( $itemList as $id => $item ){
        $itemList[ $id ] = doSomethinkWithItem( $action, $item );
    }
}

function doSomethinkWithItem( $action, $item ){
    $item->{$action} = 'someText';
}

class Items {
    private static $arItems;

    public static function preload(){
        // $arItems выборка из базы
        foreach($arItems as $ID => $data){
            $one = new \stdClass();
            $one->id  = $ID;
            $one->name = $data["NAME"];

            self::$arItems[ $ID ] = $one;
        }
    }

    public static function getItems(){
        return self::$arItems;
    }
}

Problem:
When re-retrieving the list of items using the $itemList = Items::getItems();
the elements retain their properties after being processed by the first method, but I need it to be unchanged and initially set at the time of starting work with the list. Because while working with it, some characteristics change, some elements are removed altogether.
Who can tell what is wrong with the structure and how to make sure that the initially generated list does not change at all and always gives the same one?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Melkij, 2016-05-18
@DmitryPRG

It's obvious from your doSomethinkWithItem function that the $item argument is an object.
Objects are always passed by reference. To create a copy of an object - there is a clone operator

A
Anton B, 2016-05-18
@bigton

You show the implementation of getItems, apparently the function returns not an array, but a link.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question