note 70511 added to functions.arguments

From: Date: Thu, 19 Oct 2006 09:59:39 +0000
Subject: note 70511 added to functions.arguments
Groups: php.notes 
Request: Send a blank email to php-notes+get-118745@lists.php.net to get a copy of this message
I ran into the problem that jcaplan mentionned. I had just finished building 2 handler classes and one interface. During my testing I realized that my handlers were not initializing their variables to their default values when my interface was calling them with 'null' values: this is a simplified illustration: <?php function some_function($v1='value1',$v2='value2',$v3='value3'){ echo $v1.', '; echo $v2.', '; echo $v3; } some_function(); //this will behave as expected, displaying 'value1, value2, value3' some_function(null,null,null); //this on the other hand will display ', ,' since the variables will take the null value. ?> I came to about the same conclusion as jcaplan. To force your function parameters to take a default value when a null is passed you need to include a conditionnal assignment inside the function definition. <?php function some_function($v1='value1',$v2='value1',$v3=null){ $v1=(is_null($v1)?'value1':$v1); $v2=(is_null($v2)?'value2':$v2); $v3=(is_null($v3)?'value3':$v3); echo $v1; echo $v2; echo $v3; } /* The default value whether null or an actual value is not so important in the parameter list, what is important is that you include it to allow a default behavior. The default value in the declaration becomes more important at this point: */ ?> ---- Server IP: 216.235.15.211 Probable Submitter: 216.99.40.252 ---- Manual Page -- http://www.php.net/manual/en/functions.arguments.php Edit -- https://master.php.net/note/edit/70511 Del: integrated -- https://master.php.net/note/delete/70511/integrated Del: useless -- https://master.php.net/note/delete/70511/useless Del: bad code -- https://master.php.net/note/delete/70511/bad+code Del: spam -- https://master.php.net/note/delete/70511/spam Del: non-english -- https://master.php.net/note/delete/70511/non-english Del: in docs -- https://master.php.net/note/delete/70511/in+docs Del: other reasons-- https://master.php.net/note/delete/70511 Reject -- https://master.php.net/note/reject/70511 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#118745) next »