问题
First a simple example:
function doReturnSomething()
{
// some logic
if ($resultFromLogic) {
return Default_Model_Something;
}
return false;
}
As you can see, this functions returns a model or false. Now, let's call this function from some place else:
$something = doReturnSomething();
No, I want to put a if-statement to check the variable $something. Let's say:
if (false !== $something) {}
or
if ($something instanceof Default_Model_Something) {}
or
...
Is there a "best practice" for this situation to do? Check for false or use instance of. And are there any consequences for that particular way?
Thank is advance!
回答1:
Depending on what it is returning, you could just do this:
if(doReturnSomething()) {}
It will return true when an object is returned (Default_Model_Something) and return false when false is returned or a null-value. Just don't use this way when working with numbers because "0" will evaluate to false.
回答2:
I think that from PHP 5.4 on there is a special notice error for threating a function return in logical statements.
Good pratice is to save result of a function to variable and then use it in any logical statement.
回答3:
<?php function my($a, $b ,$c){
$total = $a + $b - $c; return $total; }
$myNumber = 0;
echo "Before the function, myNumber = ". $myNumber ."<br />";
$myNumber = my(3, 4, 1); // Store the result of mySum in $myNumber
echo "After the function, myNumber = " . $myNumber ."<br />";
?>
来源:https://stackoverflow.com/questions/8880060/php-function-return-value-how-to-check