Home > Enterprise >  php array_slice modifies the global variable which was assigned by value to the variable in the arra
php array_slice modifies the global variable which was assigned by value to the variable in the arra

Time:05-18

Considering the code below:

// build post global
global $post;
$post = (object) array(
    'posts' => array_map(function($thingy){
        return (object) array('name' => $thingy);
    }, array('thingy1', 'thingy2', 'thingy3', 'thingy4', 'thingy5', 'thingy6', 'thingy7', 'thingy8')),
);

// assign post global to new variable
$index_post = $post;

error_log(var_export('post posts before slice', true));
error_log(var_export(count($post->posts), true));

// assign to new variable again
$index_post_posts = $index_post->posts;
// slice & reassign
$index_post->posts = array_slice($index_post_posts, 5, 2);

error_log(var_export('post posts after slice', true));
error_log(var_export(count($post->posts), true));

Output:

'post posts before slice'
8
'post posts after slice'
2

Expected output:

'post posts before slice'
8
'post posts after slice'
8

Why is the value of $post->posts changing when $index_post_posts has array_slice called on it? Are globals always assigned by reference in php or something? How does one get around this limitation? Thanks in advance!

CodePudding user response:

https://medium.com/@mena.meseha/reference-passing-of-objects-in-php-b57f5ab6b47e assigning objects are always passed by reference in php... use the clone keyword to bypass this

CodePudding user response:

try this $index_post = clone $post;

  •  Tags:  
  • php
  • Related