extract() to object variables

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bilibytes
    New Member
    • Jun 2008
    • 128

    extract() to object variables

    Hi everyone,

    I am wondering if it is possible to extract the key values of an array into object variables.

    lets say i have the following $_REQUEST array:

    Code:
    $var_array = array("color" => "blue",
                       "size"  => "medium",
                       "shape" => "sphere");
    extract($var_array, EXTR_IF_EXISTS);
    and the the following object:

    Code:
    Class Listener
    {
    	public $color;
            public $size;
    	
    	public function __construct(){
    		if(isset($_REQUEST)){
    
    			extract($_REQUEST,  EXTR_IF_EXISTS);
    			return true;
    		}
    		else{
    			
    			return false;
    			
    		}
    	}
    	
    }

    how could i use extract, to store the Key=>values into the object variables:

    Code:
    echo $this->color //blue
    echo $this->size //medium

    thankyou
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hi.

    You can simply loop through the array and add each array element as a property.

    For example:
    [code=php]
    class foo
    {
    public function __construct($in Array)
    {
    foreach($inArra y as $_key => $_value)
    {
    $this->$_key = $_value;
    }
    }
    }
    $arr = array('color' => 'blue', 'size' => 'medium');
    $inst = new foo($arr);
    print_r($inst);
    [/code]
    Which should give you:
    Code:
    foo Object
    (
        [color] => blue
        [size] => medium
    )
    Last edited by Atli; Nov 6 '08, 08:09 PM. Reason: Made the example clearer.

    Comment

    • bilibytes
      New Member
      • Jun 2008
      • 128

      #3
      Thankyou,

      the problem is that i cannot use the IF_EXISTS ability from the extract() function.

      if i have a request[key] that is not expected, i would store it, which is a thing i would like to avoid...

      thanks any way.

      Comment

      • Atli
        Recognized Expert Expert
        • Nov 2006
        • 5062

        #4
        Then why don't you just pick out the elements you want and leave the rest?

        Check out the array_intersect _key function.
        It should do the trick.

        Comment

        Working...