[ create a new paste ] login | about

Link: http://codepad.org/t7KdNMwV    [ raw code | output | fork ]

PHP, pasted on May 9:
<?php
  
  $object = new myClass();

  $object->setOption("mySetting.mySettingsChild.mySettingsGrandChild","foobar");

  echo "<pre>".print_r($object->options,true)."</pre>";
  


  class myClass {

     function __construct() {
        $this->setOption("grandparent.parent.child","someDefault");
     }

    function _setOption(&$array_ptr, $key, $value) {

        $keys = explode('.', $key);

        $last_key = array_pop($keys);

        while ($arr_key = array_shift($keys)) {
            if (!array_key_exists($arr_key, $array_ptr)) {
                $array_ptr[$arr_key] = array();
            }
            $array_ptr = &$array_ptr[$arr_key];
        }

        $array_ptr[$last_key] = $value;
    }
    
    function setOption($key,$value) {
        
        if (!isset($this->options)) {
            $this->options = array();
        }
        
        $this->_setOption($this->options, $key, $value);
        return true;                        
    }

  }


?>


Output:
<pre>Array
(
    [grandparent] => Array
        (
            [parent] => Array
                (
                    [child] => someDefault
                )

        )

    [mySetting] => Array
        (
            [mySettingsChild] => Array
                (
                    [mySettingsGrandChild] => foobar
                )

        )

)
</pre>


Create a new paste based on this one


Comments: