PHP, when NULL is not enough
Let’s say the next exercise
function someFunction($field1,$field2=null,$field3=null) {
// we do something here
}
So, we could use the null as expected. A NULL conceptually (for this case) is a value that has not be fixed. And in this example, we could call the function as
someFunction(‘some value’);
And we know that $field2 is missing because it’s NULL (the second argument is not set). PHP doesn’t have the concept of method overload so that NULL could help (instead of counting the number of arguments). So, the function could works different instead of if we call with the second arguments
someFunction(‘some value’,’another value’);
But what if NULL is considered a valid value (versus as no-set). For example
function someFunction($field1,$field2=null,$field3=null) {
// we inserted the value into the database, i.e. insert into tabla (field1,field2) values($field1,$field2)
}
So we could call it as
someFunction(‘some value’,null);
Where null is not a missing argument but a valid value.
My solution was to use a new NULL value
function someFunction($field1,$field2=self:NULL,$field3=self:NULL) {
// we do something here
}
where NULL is a constant.
It’s not perfect but it works.