Fill the array item with dependencies on other items in PHP

Viewed 58

I have an array and want to fill the some items depend on previous item's values:

$order = array(
    'items_price' => 200,
    'tax_price' => 18,
    'total_price' => function () { 
        return $order.items_price + $order.tax_price;
    })

How can I do that?

1 Answers

Well, that actually is doable. You cannot reference values in the array from within the array itself; but if you declare variable references for the needed array values, you can pass those references to the closure (function) using use :

$order = array(
  'items_price' => ($ip = 200),
  'tax_price' => ($tp = 18),
  'total_price' => function() use ($ip, $tp) {
     return $ip + $tp;
  }
);
echo $order['total_price']();

That echoes out 218 ..! But the downside is that the passed references / params are static. Try

$order['items_price'] = 100;
echo $order['total_price']();

The result are a disappointing 218 ... Even though items_price actually are changed to 100, the params passed to total_price are the same as when the array were created. They are not magically updated, the array are not a piece of dynamic code, it is a data structure.

It was a very interesting question indeed, but I do not see any practically use. It seems to me you in this case should use classes instead of arrays.

Related