Good day!
Faced with the strange behavior of PHP. Well, or with his full competence in this matter.
Asking for help from knowledgeable people.
Thanks in advance.
The essence of the situation.
Shape is static class Items
he has 2 static functions
Items::preload() - generates an array of elements and records in a private class property
Items::getItems() - returns a list of elements generated by the first function
Now that is not working 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 );
}
}
doSomethinkWithItem function( $action, $item ){
$item->{$action} = 'someText';
}
class Items {
private static $arItems;
public static function preload(){
// $arItems fetching from the database
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 you re retrieving a list of elements using $itemList = Items::getItems();
the items are stored properties after processing the first method, and I must be at the beginning of the list, he was a constant and preset. Because while working with him, some characteristics change, some elements will be removed at all.
Who can tell what is wrong with the structure and how to make so that initially compiled the list was not changed at all and was given always the same?
But I can't really imagine how you can copy a static class?
Can you tell?
$itemList = clone Items::getItems(); - clear throws an error that it is not an object - Harmony.Champlin commented on July 9th 19 at 13:27
public static function getItems(){
return array_map(function($el) {
return clone $el;
} self::$arItems;
}
A static class is not important here. The link transmit stdClass - Ignacio_Romaguera commented on July 9th 19 at 13:30
Your approach is more like it.
well I did clone myself in a loop:
$itemList = Items::getItems();
foreach( $itemList as $id => $item ){
$item_clone = clone $item;
But eventually altered to the return function.
Once again, thank you - Harmony.Champlin commented on July 9th 19 at 13:33