1.2.47. Array_Fill() With Objects

array_fill() fills an array with identical objects, not copies nor clones. This means that all the filled objects are a reference to the same object. Changing one of them will change any of them.

Make sure this is the intended effect in the code.

This applies to array_pad() too. It doesn’t apply to array_fill_keys(), as objects will be cast to a string before usage in this case.

<?php

$x = new StdClass();
$array = array_fill(0, 10, $x);

$array[3]->y = "Set in object #3";

// displays "Set in object #3"
echo $array[5]->y;

?>

1.2.47.1. Suggestions

  • Use a loop to fill in the array with cloned() objects.

1.2.47.2. Specs

Short name

Structures/ArrayFillWithObjects

Rulesets

All, Analyze

Exakat since

2.1.9

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Features

array, object

Available in

Entreprise Edition, Exakat Cloud