Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only initialize a variable in an array if it's requested

Here's a little mock-up to describe my predicament:

<?php
$var = "Before";

function getVar(){
    global $var;

    return $var;
}

$array = Array(
    "variable" => "Var = " . getVar()
);

$var = "After";

echo $array['variable'];
?>

That code would echo 'Before', I'm aiming for it to echo 'after'. I realize that this is how PHP is supposed to work however it's crucial for the array to execute getVar() only when it's called.

How would I go about doing this?

like image 854
AlphaDelta Avatar asked Nov 01 '22 12:11

AlphaDelta


1 Answers

You can not do this since array declaration will initialize it - so you're mixing function calling at array's 'usage' and at it's definition. There's no 'usage': array is already defined to that moment.

However, an answer could be using ArrayAccess, like this:

class XArray implements ArrayAccess
{
   private $storage = [];

   public function __construct()
   {
      $this->storage = func_get_args();
   }

   public function offsetSet($offset, $value)
   {
      if(is_null($offset)) 
      {
         $this->storage[] = $value;
      } 
      else
      {
         $this->storage[$offset] = $value;
      }
   }

   public function offsetExists($offset) 
   {
      return isset($this->storage[$offset]);
   }

   public function offsetUnset($offset) 
   {
      unset($this->storage[$offset]);
   }

   public function offsetGet($offset) 
   {
      if(!isset($this->storage[$offset]))
      {
         return null;
      }
      return is_callable($this->storage[$offset])?
             call_user_func($this->storage[$offset]):
             $this->storage[$offset];
   }
}

function getVar()
{
   global $var;
   return $var;
}

$var = 'Before Init';
$array = new XArray('foo', 'getVar', 'bar');
$var = 'After Init';
var_dump($array[1]);//'After Init'

-i.e. try to call data, which is inside element, when actual get happened. You may want to have different constructor (for associative arrays) - but the general idea was shown.

like image 149
Alma Do Avatar answered Nov 08 '22 05:11

Alma Do