Extract/Import Object properties into Currect Symbol Table in PHP

If we want to import an associative array into current symbol table then we can use extract function. This function treats associative array keys as variable name and values as variable values.

But we can not use extract function directly if we want to import class object properties into current symbol table in similar way. So, for this first we need to get the properties of object as an associated array. We can use get_object_vars function for this purpose. get_object_vars function take object as parameter and return associative array of all non-static properties of passed object. For any unassigned property it will return NULL value.

Now we can pass this returned associative array into extract function to import objects non-static properties into current symbol table.

Code Snippet:-

<?php
// For associative array
 
$sampleArray = array('name' => 'John', 'age' => 25);
 
extract($sampleArray);
 
echo $name; // Output is "John"
echo $age; // Output is "25"
 
// For object
$sampleObject = new stdClass;
 
$sampleObject->name = 'Peter';
$sampleObject->age = 27;
 
$returnArray = get_object_vars($sampleObject);
 
extract($returnArray);
 
echo $name; // Output is "Peter"
echo $age; // Output is "27"
?>

,


  1. No comments yet.
(will not be published)

 


Submit Comment
Subscribe to comments feed
  1. No trackbacks yet.