Reputation: 1525
I am aware that some built-in php functions have mixed return type, such as strpos()
.
Is there some sort of a 'Best Practice' on returning values from a custom php function?
Take a look at this
function getSupportedCurrencies() {
// code here
}
The getSupportedCurrencies()
expects an array
of currencies to be returned.
But if there is no supported currencies, we can easily return false
or null
.
But semantically, we should return an empty array()
.
I understand that PHP variables are loosely typed allowing the program to be flexible.
But what benefits does a loosely typed function provide? Does it just only give
programmers an opportunity to write bad code
? Please give an example wherein it is
needed to have mixed return type. Thanks.
Upvotes: 1
Views: 442
Reputation: 5524
Personally, when working with functions which accept arrays. I'd prefer something like:
function GetCur ($Argument = array()){
$Errors = 0;
if (!is_array($Argument)){
// If is not an array then increment the errors
$Errors++;
}
if (empty($Argument)){
// If passed array is empty then increment
$Errors++;
}
if ($Errors >0){
// If errors are higher than 0, then return false
return false;
}
// Do other validations that you need your function to do
}
Then validate as so:
if (GetCur($Array) !== false){
// function has not returned false, so correct information has been passed
}else{
// Function has returned false, so incorrect information has been passed. So log/show a error
}
a simple comparison would be to look at the workings for Strpos which specifies:
Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
Please note, this is an example. There are more efficient ways to handle countless if statements within a function, which would also provide better readability if you are creating an API
Upvotes: 0
Reputation: 9168
There is no really way to be typesafe in PHP as you mean, no really security that returned value is of wrong type. You may want to look at some extra tool like HipHop compiler (or to some other language).
Upvotes: 1