技术开发 频道

PHP开发经典教程(Part 6):编写自定义函数

return语句 

    上述页面的函数只是简单的将它们的结果输出到屏幕上。但是如果你想让函数对结果做一些其他的事情会怎么样呢?那么在PHP中,你可以让函数返回一个值(诸如运算结果)给调用它的语句。这可以通过在函数内使用return语句来实现,如下所示:

<?php // define a function function getCircumference($radius) { // return value return (2 * $radius * pi()); } /* call a function with an argument and store the result in a variable */ $result = getCircumference(10); /* call the same function with another argument and print the return value */ print getCircumference(20); ?>

 
    这里,处理传递给函数getCircumference()的参数,然后将结果返回给主程序,在主程序里面该结果在一变量中可以通过其他方式被捕捉、打印或处理。 

    你甚至可以在另外函数内部使用一个函数的结果,这一点在下面稍微对上面例子修改的代码中得到举例说明:

<?php // define a function function getCircumference($radius) { // return value return (2 * $radius * pi()); } // print the return value after formatting it print "The answer is ".sprintf("%4.2f", getCircumference(20)); ?>

    返回值不需要单独是数字或字符串:函数也可以像下面例子示范的那样容易的返回数组。还记得它们吗?

<?php /* define a function that can accept a list of email addresses */ function getUniqueDomains($list) { /* iterate over the list, split addresses and add domain part to another array */ $domains = array(); foreach ($list as $l) { $arr = explode("@", $l); $domains[] = trim($arr[1]); } // remove duplicates and return return array_unique($domains); } // read email addresses from a file into an array $fileContents = file("data.txt"); /* pass the file contents to the function and retrieve the result array */ $returnArray = getUniqueDomains($fileContents); // process the return array foreach ($returnArray as $d) { print "$d, "; } ?>
    假定文件如下面所示那样:
test@test.com
a@x.com
zooman@deeply.bored.org
b@x.com
guess.me@where.ami.net
testmore@test.com

    而脚本的输出结果如下:

test.com, x.com, deeply.bored.org, where.ami.net,
    请注意,return语句结束了函数内部程序的执行。
0
相关文章