note 37594 added to function.extract

From: Date: Thu, 20 Nov 2003 12:52:08 +0000
Subject: note 37594 added to function.extract
Groups: php.notes 
Request: Send a blank email to php-notes+get-60685@lists.php.net to get a copy of this message
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. ---- Manual Page -- http://www.php.net/manual/en/function.extract.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+37594 Delete -- http://master.php.net/manage/user-notes.php?action=delete+37594&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+37594&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#60685) next »