首页 >后端开发 >php教程 >php函数间的参数传递(值传递/引用传递)_PHP教程

php函数间的参数传递(值传递/引用传递)_PHP教程

WBOY
WBOY原创
2016-07-21 16:12:49809浏览

php:函数间的参数传递

1.值传递

复制代码 代码如下:

function exam($var1){
$var1++;
echo "In Exam:" . $var1 . "
";
}

$var1 = 1;
echo $var1 . "
";
exam($var1);
echo $var1 . "
";
?>

-------------------------------------------------------------------------------
输出结果:
1
In Exam: 2
1
-------------------------------------------------------------------------------
2.引用传递
复制代码 代码如下:

function exam( &$var1){
$var1++;
echo "In Exam:" . $var1 . "
";
}

$var1 = 1;
echo $var1 . "
";
exam($var1);
echo $var1 . "
";
?>


-------------------------------------------------------------------------------
输出结果:
1
In Exam: 2
2
-------------------------------------------------------------------------------
3.可选参数
复制代码 代码如下:

function values($price, $tax=""){
$price += $prive * $tax;
echo "Total Price:" . $price . "
";
}

values(100, 0.25);
values(100);

输出结果:
Total Price: 125
Total Price: 100
-------------------------------------------------------------------------------
4.如果传入的是一个对象,可以更改该对象的值
(实际上变量$obj记录的是这个对象的句柄,将$obj作为参数传入,完全可以对原对象进行操作。)
复制代码 代码如下:

class Obj{
public $name;
public $age;
public $gander;
public function __construct($name, $age, $gander){
$this->name = $name;
$this->age = $age;
$this->gander = $gander;
}
public function show_info(){
echo $this->name . " " . $this->age . " " . $this->gander . "
";
}
}
function grow($obj){
$obj->age++;
}
function test(){
$obj = new Obj("Mr. zhan", "12", "male");
$obj->show_info();
grow($obj);
$obj->show_info();
grow($obj);
$obj->show_info();
}
test();
?>

-------------------------------------------------------------------------------
输出结果:
Mr. zhan 12 male
Mr. zhan 13 male
Mr. zhan 14 male

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/313595.htmlTechArticlephp:函数间的参数传递 1.值传递 复制代码 代码如下: ?php function exam($var1){ $var1++; echo "In Exam:" . $var1 . "br /"; } $var1 = 1; echo $var1 . "br /"; exam($v...
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn