PHP function return value, how to check

99封情书 提交于 2021-01-29 05:58:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!