Possible Duplicate:
default method argument with class property?
I’m writing a recursive function and just for ease of use I want the first call of the function to accept a default argument. This value has to be the address of an object member variable. See below full code:
class Test{
public $hierarchy = array( );
public function addPath( $path, &$hierarchy ){
$dirs = explode( '/', $path );
if( count( $dirs ) == 1 ){
if( is_dir( $path ) )
$hierarchy[ $dirs[ 0 ] ] = '';
else
$hierarchy[ $path ] = '';
return $hierarchy;
}
$pop = array_shift( $dirs );
$hierarchy[ $pop ] = $this->addPath(
implode( '/', $dirs ), $hirearchy[ $pop ] );
return $hierarchy;
}
}
$t = new Test( );
$t->addPath( '_inc/test/sgsg', $t->hierarchy );
print_r( $t->hierarchy );
Now, what I would like to do here ideally is add a default value:
public function addPath( $path, &$hierarchy = $this->hierarchy ){
So that I can call it like this:
$t->addPath( '_inc/test/sgsg' );
But this gives me the following error:
Parse error: syntax error, unexpected '$this' (T_VARIABLE) in tst.php on line 9
I’ve been trying a few things with no success. Is there any way I can achieve this?
Unfortunately you cannot do this, the parser does not (cannot!) cater for resolving variables in function definitions.
You can however define the function with
&$hierarchy = nullin the definition and useis_nullto see if a value was passed. (unless your referenced value will sometimes be null, then you’ll need another workaround)If
is_nullreturns true then you can assign$hierarchy = &$this->hierarchyAfter a quick discussion in PHP chat, using
func_num_args()might be useful here. It doesn’t count args that are populated with defaults, so you can safely pass variables that containnullby reference, and use this function to determine if the value in$hierarchycame from a passed parameter, or by the default. (thanks @NikiC)