Answer the question
In order to leave comments, you need to log in
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;
}
}
Answer the question
In order to leave comments, you need to log in
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question