note 37594 deleted from function.extract by aidan
| From: | aidan@php.net | Date: | Thu, 09 Sep 2004 09:14:25 +0000 |
| Subject: | note 37594 deleted from function.extract by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-76291@lists.php.net to get a copy of this message | ||
Note Submitter: marxy at portugalmail dot pt
----
I would like to extract an associative array into the properties of an object
<?
class MyClass
{
$var property1;
$var property2;
function MyClass( $array )
{
extract( $array )
}
}
$properties = array( 'property1'=>"red",
'property2'=>'blue')
$c = new MyClass( $propertries );
print_r( $c );
?>
This won't work cause, property1(="red") and property2(="blue") will only
be available inside the constructor.
The way to do it is:
<?
class MyClass
{
$var property1;
$var property2;
function MyClass( )
{
if( func_num_args( ) > 0 )
{
$array = func_get_arg( 0 );
foreach( $array as $key => $value )
{
$this->$key = $value;
}
}
else
{
die("on args in");
}
}
$properties = array( 'property1'=>"red",
'property2'=>'blue')
$c = new MyClass( $propertries );
print_r( $c );
}
?>
This way you can create an object no knowing for sure how many init values (and order) you will
have.