note 70044 deleted from function.func-get-args by tularis
| From: | tularis@php.net | Date: | Fri, 15 Jul 2011 09:07:31 +0000 |
| Subject: | note 70044 deleted from function.func-get-args by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-181559@lists.php.net to get a copy of this message | ||
Note Submitter: kidekat
----
To pass named arguments in a Perl fashion through class constructors, I use this:
<?php
class Test{
// set class defaults for values not assigned by constructor
public $a = 0;
public $b = 'string';
public $c = array();
public function __construct( $args = array() ) {
// parse tagged arguments in Perl fashion
foreach( $args as $k => $v ){
switch($k){
case 'a':
$this->a= $v; break;
case 'b':
$this->b= $v; break;
case 'c':
$this->c= $v; break;
}
}
}
}
$t = new Test( array( 'b'=>'new value',
'c'=>array(1,'test') ) );
?>
This allows $a to keep its default of 0, while $b gets reassigned to 'new value' and $c
becomes the array(1,'test'). The catch is that you add O(n^2) "big-O notation"
to the begging of every class constructor which becomes expensive on "larger" classes.
While arguments defaults like the following have only O(n) "constant" amount of work.
<?php
public funciton __construct( $a=0, $b='string', $c=array()){ ... }
?>