php函数变量和传递
2016-01-17 15:25
555 查看
PHP
支持按值传递参数(默认),通过引用传递参数以及默认参数。也支持可变长度参数列表。
引用传递
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
默认参数:
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
默认值必须是常量表达式,不能是诸如变量,类成员,或者函数调用等
Note: 自
PHP 5 起,传引用的参数也可以有默认值。
Type declarations allow functions to require that parameters are of a certain type at
call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.
e.g.,
function f(C $c) {
echo get_class($c)."\n";
}
Strict
typing
declare(strict_types=1);
try {
var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
} catch (TypeError $e) {
echo 'Error: '.$e->getMessage();
}
PHP 在用户自定义函数中支持可变数量的参数列表。在 PHP 5.6 及以上的版本中,由 ... 语法实现;在 PHP 5.5 及更早版本中,使用函数 func_num_args(),func_get_arg(),和 func_get_args()
New
version:
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>
Old
version:
function sum() {
$acc = 0;
foreach (func_get_args() as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
支持按值传递参数(默认),通过引用传递参数以及默认参数。也支持可变长度参数列表。
引用传递
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
默认参数:
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
默认值必须是常量表达式,不能是诸如变量,类成员,或者函数调用等
Note: 自
PHP 5 起,传引用的参数也可以有默认值。
Type declarations
Type declarations allow functions to require that parameters are of a certain type atcall time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.
e.g.,
function f(C $c) {
echo get_class($c)."\n";
}
Strict
typing
declare(strict_types=1);
try {
var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
} catch (TypeError $e) {
echo 'Error: '.$e->getMessage();
}
可变数量的参数列表
PHP 在用户自定义函数中支持可变数量的参数列表。在 PHP 5.6 及以上的版本中,由 ... 语法实现;在 PHP 5.5 及更早版本中,使用函数 func_num_args(),func_get_arg(),和 func_get_args() New
version:
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>
Old
version:
function sum() {
$acc = 0;
foreach (func_get_args() as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
相关文章推荐
- 一个关于if else容易迷惑的问题
- PHP5.2.*防止Hash冲突拒绝服务攻击的Patch
- 深入理解PHP之匿名函数
- JSP/PHP基于Ajax的分页功能实现
- 关于PHP通过PDO用中文条件查询MySQL的问题。
- 什么是设计模式
- PHP数据库长连接mysql_pconnect的细节
- Php Installing An Expansion
- PHP+Apache在Windows 9x下的安装和配置
- IIS 6 的 PHP 最佳配置方法
- 安装Apache和PHP的一些补充
- Linux Apache+MySQL+PHP
- 建立Apache+PHP+MySQL数据库驱动的动态网站
- PHP 5.3.0 安装分析心得
- apache 环境下 php 的配置注意事项
- ASP.NET、ASP、PHP、JSP之间有什么区别?
- PHP VBS JS 函数 对照表
- C语言实现的统计php代码行数功能源码(支持文件夹、多目录)
- php xml 入门学习资料