开发者

php style about returning multiple values

开发者 https://www.devze.com 2023-04-03 13:04 出处:网络
Perhaps this is just a stylistic question, or perhaps there is a \"right\" answer. If I have a php function that needs to return multiple values (and those are incoming args) which is preferred:

Perhaps this is just a stylistic question, or perhaps there is a "right" answer.

If I have a php function that needs to return multiple values (and those are incoming args) which is preferred:

function myFuncReturnVals ($a, $b) {
 // do stuff
 return array ($a, $b)
}

function myFuncByRef (&$a, &$b) {
 // do stuff
}

list($a,$b) = myFuncReturnVals ($a,$b);
myFuncByReb($a,$b);

Either way will get the job done, but which is preferred?

ReturnVals seems to be a little cleaner in some respects as it lets the caller decide if their values are going to be modified.

However, sometimes by ref seems to fit better as the intent of the function is really to muc开发者_开发知识库k with that data.

What about mixing and matching? What if you have a function that mostly is responsible for giving back some data, but in process might have additional information about the incoming parameter?


I tend to avoid reference parameters like the plague: it's obvious what they do at the point where you're defining them, but most of the time, you'll be looking at their usage, and there it isn't clear at all whether those parameters are by-reference or by-value.

Sticking to the return-as-array paradigm is more readable, and makes it easier to avoid side effects; it also allows nesting / chaining function calls - the kind of style that looks like this in action:

$output = nl2br(
          detect_links(
          htmlspecialchars(
          trim($input))))

If you have more than one function returning the same kind of value collection, it may be worth wrapping them in a class - this way, your return value becomes more descriptive even without (phpdoc) comments, and you will be able to catch invalid input to other functions that consume such values by adding type hints to the function argument.

Also, note that objects are reference types already, so passing them by reference only makes sense if you want to replace the entire object - altering individual fields or calling destructive methods will alter the original object even if you had passed it by value. Example:

<?php
class Bar {
    public $x;
    public function __construct($x) { $this->x = $x; }
}

function foo($bar, $x) {
    $bar->x = $x;
}

$myBar = new Bar(23);
$foo($myBar, 42);
printf("$foo->x is now %s\n", $foo->x);


Matter of choice. Use the method which is consistent with your coding style. I would rather return an array.

0

精彩评论

暂无评论...
验证码 换一张
取 消