可变参数
可以使用以下函数来获取可变参数 func_num_args()、 func_get_arg() 和 func_get_args(),不建议使用此方式,请使用 ... 来替代。
<?php
function sum(...$numbers)
{
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
/**
*计算任意多个数的和,并返回计算后的结果
*/
function sum() { //这里的括号中没有定义任何参数
echo "输入参数个数:",func_num_args(),"结果:"; //输出参数个数
$total = 0;
$varArray = func_get_args(); //使用func_get_args()来获取当前函数的所有实际传递参数,返回值为array类型
foreach ($varArray as $index => $var) {
$total += func_get_arg($index); //获取单个参数
//$total += $var;
}
return $total;
}
/*****下面是调用示例*****/
echo sum(1, 3, 5); //计算1+3+5
echo sum(1, 2); //计算1+2
echo sum(1, 2, 3, 4); //计算1+2+3+4
/**
*计算任意多个数的和,并返回计算后的结果
*/
function sum($a, $b) {
return array_sum(func_get_args());
}
可变变量
可变变量的概念:通过获取一个变量的值做为另外一个变量的名称来操作变量,就是可以变量。
<?php
$method = "save" . ucfirst($data_type['input_table']) . "_" . $file_info['file_type'];
$this->$method($file_info);
for ($i = 1; $i < 5; $i++) {
$name = "name_" . $i;
$$name = 'test' . $i;
}
$result = $this->_statement->{$method}($mode);
eval('$this->' . $_GET['flashreport'] . '();');
<?php
$a = 'hello' ; //普通变量
$$a = 'world' ; //可变变量 ,相当于 $hello='world';
echo "$a $hello" ; //输出:hello world
echo $$a ; //输出:world
echo "$a ${$a}" ; //输出:hello world
echo "$a {$$a}" ; //输出:hello world
$string = "beautiful";
$time = "winter";
$str = 'This is a $string $time morning!';
echo $str. "<br />";
eval("\$str = \"$str\";");
echo $str;
This is a $string $time morning!
This is a beautiful winter morning!
eval('$a=55;');
可变函数
<?php
function echoit($string)
{
echo $string;
}
$func = 'echoit';
$func('test'); // This calls echoit()
?>
<?php
class Foo
{
static $variable = 'static property';
static function Variable()
{
echo 'Method Variable called';
}
}
echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope.
$variable = "Variable";
Foo::$variable(); // This calls $foo->Variable() reading $variable in this scope.
CGI模式下argc和argv
- argc: 整数,用来统计你运行程序时送给main函数的命令行参数的个数
- argv: 字符串数组,用来存放指向你的字符串参数的指针数组,每一个元素指向一个参数
php index.php 1 10 100
<?php
echo $argv[0]; echo "\n";
var_dump($argv[1]); echo "\n";
var_dump(intval($argv[2])); echo "\n";
echo $argv[3]; echo "\n";
echo $argc;
index.php //$argv[0]显示结果 经测试此处显示的是此脚本相对于执行位置的相对路径(就是你在哪里输入的php index.php,这里显示的就是 index.php 相对于你当前目录的位置)
string(1) "1" //$argv[1]显示第一个参数会转为字符串
int(10) //$argv[2]显示第二个参数
100 //$argv[3]显示第二个参数
4 //$argv参数的个数 相对路径+你传的参数