php 中函数获取可变参数的方法, 这个语法有点像 golang 语言中的
原文呢:http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.strict
Only valid typehint for boolean
is bool
. As per documentation boolean
isn't recognized as alias of bool
in typehints. Instead it is treated as class name. Same goes for int
(scalar) and integer
(class name), which will result in error
TypeError: Argument 1 passed to a() must be an instance of integer, integer given
In this specific case object of class boolean
is expected but true
(bool, scalar) is passed.
Valid code is
<?php
function a(bool $value){
var_dump($value);
}
a(true);
which result is
bool(true)
--------------------------------------------------------------------------------
1. php函数调用中获取变长参数的方法, ...token ,类似于golang语言中的。
2. php 中也有类似与javascript 中的 "use strict ";严格模式。
Strict typing¶
By default, PHP will coerce values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string.
It is possible to enable strict mode on a per-file basis. In strict mode, only a variable of exact type of the type declaration will be accepted, or a TypeError will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float. Function calls from within internal functions will not be affected by the strict_types declaration.
To enable strict mode, the declare statement is used with the strict_types declaration:
<?php
declare(strict_types=1); function sum(int $a, int $b) {
return $a + $b;
} var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
?>
3.Type declarations¶
Note:
Type declarations were also known as type hints in 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.
To specify a type declaration, the type name should be added before the parameter name. The declaration can be made to accept NULL
values if the default value of the parameter is set to NULL
.
Valid types¶
Type | Description | Minimum PHP version |
---|---|---|
Class/interface name | The parameter must be an instanceof the given class or interface name. | PHP 5.0.0 |
self | The parameter must be an instanceof the same class as the one the method is defined on. This can only be used on class and instance methods. | PHP 5.0.0 |
array | The parameter must be an array. | PHP 5.1.0 |
callable | The parameter must be a valid callable. | PHP 5.4.0 |
bool | The parameter must be a boolean value. | PHP 7.0.0 |
float | The parameter must be a floating point number. | PHP 7.0.0 |
int | The parameter must be an integer. | PHP 7.0.0 |
string | The parameter must be a string. | PHP 7.0.0 |
iterable | The parameter must be either an array or an instanceof Traversable. | PHP 7.1.0 |
Warning
Aliases for the above scalar types are not supported(意思是: 只能用int, 而不能用integer, 只能用bool,不能用boolean.). Instead, they are treated as class or interface names. For example, using boolean as a parameter or return type will require an argument or return value that is an instanceof the class or interface boolean, rather than of type bool:
<?php
function test(boolean $param) {}
test(true);
?>
The above example will output:
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given, called in - on line 1 and defined in -:1
---------------------------------------------------------------------------------------------------------------
... in PHP 5.6+¶
In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:
Example #13 Using ... to access variable arguments
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>
The above example will output:
10
You can also use ... when calling functions to unpack an array or Traversable variable or literal into the argument list:
Example #14 Using ... to provide arguments
<?php
function add($a, $b) {
return $a + $b;
}
echo add(...[1, 2])."\n";
$a = [1, 2];
echo add(...$a);
?>
The above example will output:
3
3
You may specify normal positional arguments before the ... token. In this case, only the trailing arguments that don't match a positional argument will be added to the array generated by ....
It is also possible to add a type hint before the ... token. If this is present, then all arguments captured by ... must be objects of the hinted class.
Example #15 Type hinted variable arguments
<?php
function total_intervals($unit, DateInterval ...$intervals) {
$time = 0;
foreach ($intervals as $interval) {
$time += $interval->$unit;
}
return $time;
}
$a = new DateInterval('P1D');
$b = new DateInterval('P2D');
echo total_intervals('d', $a, $b).' days';
// This will fail, since null isn't a DateInterval object.
echo total_intervals('d', null);
?>
The above example will output:
3 days
Catchable fatal error: Argument 2 passed to total_intervals() must be an instance of DateInterval, null given, called in - on line 14 and defined in - on line 2
Finally, you may also pass variable arguments by reference by prefixing the ... with an ampersand (&).
Older versions of PHP¶
No special syntax is required to note that a function is variadic; however access to the function's arguments must use func_num_args(), func_get_arg() and func_get_args().
The first example above would be implemented as follows in PHP 5.5 and earlier:
Example #16 Accessing variable arguments in PHP 5.5 and earlier
<?php
function sum() {
$acc = 0;
foreach (func_get_args() as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>
The above example will output:
10
php 中函数获取可变参数的方法, 这个语法有点像 golang 语言中的的更多相关文章
- golang中函数的可变参数
package main import "fmt" // 一个函数中最多只可有一个可变参数, 如果参数列表中还有其它类型的参数,则可变参数写在最后 // 注意:参数不定,参数的个数 ...
- Spring 中Controller 获取请求参数的方法笔记
1.直接把表单的参数写在Controller相应的方法的形参中,适用于get方式提交,不适用于post方式提交.若"Content-Type"="application/ ...
- Keil c中自定义带可变参数的printf函数
在嵌入式c中,往往采用串口打印函数来实现程序的调试,而在正式程序中一般是不需要这些打印代码的,通常做法是在这些调试用打印代码的前后设置一个宏定义块来实现是否启用这段代码,比如: // other us ...
- 使用jquery获取url以及jquery获取url参数的方法
使用jquery获取url以及使用jquery获取url参数是我们经常要用到的操作 1.jquery获取url很简单,代码如下 1.window.location.href; 其实只是用到了javas ...
- lua --- 函数的可变参数
主要掌握: 1>虚变量 --- 一个下划线 2>lua将函数的可变参数放在一个叫 arg 的表中,除了参数以外,arg表中还有一个域n表示参数的个数. do function fun(x, ...
- 使用jquery获取url以及jquery获取url参数的方法(转)
使用jquery获取url以及使用jquery获取url参数是我们经常要用到的操作 1.jquery获取url很简单,代码如下 1.window.location.href; 其实只是用到了javas ...
- Python学习之路:函数传递可变参数与不可变参数
函数传参的方法: 太基础了,8说了 直接上重点 一.可变参数的传递 可变参数有:列表.集合.字典 直接上代码: a = [1, 2] def fun(a): print('传入函数时a的值为:', a ...
- jsp中四种传递参数的方法
jsp中四种传递参数的方法如下: 1.form表单 2.request.setAttribute();和request.getAttribute(); 3.超链接:<a herf="i ...
- js获取url参数的方法
js获取url参数的方法有很多. 1.正则分析 function getQueryString(name) { var reg = new RegExp("(^|&)" + ...
随机推荐
- 【js】【ios】【safari】【兼容问题】【转发】JS IOS/iPhone的Safari不兼容Javascript中的Date()问题
引用地址:http://www.cnblogs.com/yiven/p/6053872.html 1 var date = new Date('2016-11-11 11:11:11'); 2 d ...
- 细说unittest-2
一.unittest模块官方文档: https://docs.python.org/3/library/unittest.html 二.一张图看懂unittest: 三.Unittest主要方法属性: ...
- eclipse代码格式化快捷键无法使用
[产生原因] Ctrl+Shift+F快捷键组合被其他应用占有,如输入法. [解决方案] 关闭或更换其他应用快捷键或更换eclipse对应的快捷键组合.
- CodeForces 484B 数学 Maximum Value
很有趣的一道题,题解戳这. #include <iostream> #include <cstdio> #include <cstring> #include &l ...
- Myeclipse 添加Android开发工具
1.JDK是必须的,同时配置相应环境变量. 2.Android SDK 下载后解压缩需要把SDK目录下的tools和platform-tools加入环境变量. 3.MyEclipse中安装ADT插件 ...
- NOS跨分区灾备设计与实现
本文来自网易云社区 作者:王健 摘要 NOS(网易对象存储)在实现多机房(杭州机房,北京机房等)部署后,允许一个用户在建桶时选择桶所属机房.在此基础上,我们实现了跨机房的数据复制,进一步实现了跨机房的 ...
- java编程思想阅读记录
第五章:初始化与清理 1.构造器确保初始化 构造器采用与类名相同的方法. 创建对象时,将会为对象分配存储空间,并调用相应的构造器.这就确保了在你能操作对象之前,它就已经恰当的被初始化了. 垃圾回收器负 ...
- POJ-1236 Network of Schools,人生第一道Tarjan....
Network of Schools 题意:若干个学校组成一个计算机网络系统,一个学校作为出发端连接着若干个学校,信息可以传送到这些学校.被链接的学校不需要再次与出发端相连,现在问你:A:最少选几个学 ...
- 只操作git(cmd)就可以使用git将项目上传到github
代码改变世界 使用git将项目上传到github(最简单方法) 首先你需要一个github账号,所有还没有的话先去注册吧! https://github.com/ 我们使用git需要先安装git工具, ...
- 分析Tapjoy的模式—分发用于ios设备的企业级应用程序
下面简单介绍下Tapjoy的模式,供大家参考: Tapjoy最初的合作模式:“按安装奖励”(pay-per-install) Tapjoy利用非常成功的奖励性下载模式影响了App Store的免费游戏 ...