note 70511 deleted from functions.arguments by cmb
| From: | cmb@php.net | Date: | Sun, 10 Nov 2019 13:19:59 +0000 |
| Subject: | note 70511 deleted from functions.arguments by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-213026@lists.php.net to get a copy of this message | ||
Note Submitter: keuleu at hotmail dot com
----
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:
*/
?>