View Full Version : Opptional Arguments Defining Functions

10-08-2004, 02:26 AM
Now Im turning into a guy who makes a lot of functions and classes and I've stumbled upon errors when leaving so of my own function arg's blank....now I know all the predefined functions make arg's opptional, so how can I make my function arg's opptional and I'm making them in classes so inc. that...

Thanks In Advance

10-08-2004, 04:16 AM
note that you can't have optional args passed by reference so you can't do &$optional_arg='' etc otherwise ...

function blah( $arg1 , $optional_arg='' , $optional_arg2='' ){
if( !empty( $optional_arg ) ){
blah( 'yaks' ) ;
blah( 'yaks' , 'yaks' ) ;
blah( 'yaks' , '' , 'yaks' ) ;

this can get confusing sometimes so I like to use null when not passing an arg (so all calls at least look the same)
blah( 'yaks' , null , 'yaks') ;
but then you should be checking for is_null() within your function

And some will say the above is bad juju , perhaps thats true , I am now in the habit of passing a optional array of data instead , this makes things far easier to refactor if you need to another argument to a common function at some future point and do not want to trawl your code changing function calls to do so

$optional_args = array('arg2'=>'blah','arg3'=>'blah') ;
blah('yaks' , $optional_args ) ;

10-08-2004, 07:47 AM
Firepages second example is the same thing I use and it really works great. It makes adding args to class methods very easy plus you can do things like this:

class objSQL() {

function edit($table,$values) { //$values could equal $_POST or some other Global array
$sql = "UPDATE $table ";
$sql .= " SET";
foreach($values as $key=>$value) {
${$key} = htmlentities($value);
$sql .= " $key='" . ${$key} . "',";
$sql = substr( $sql,0,(strlen($sql)-1) ); //Remove the last comma
$sql .= " WHERE {$this->unique}='". $this->uniquid . "'"; //Primary Key

return $this->query($sql);


EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum