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

编程学习 2021-07-05 09:49www.dzhlxh.cn编程入门
函数间的参数传递包括值传递和引用传递,详细示例接下来为大家详细介绍下,感兴趣的朋友不要错过
php:函数间的参数传递

1.值传递
代码如下:

<?php
function exam($var1){
$var1++;
echo "In Exam:" . $var1 . "<br />";
}

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

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

<?php
function exam( &$var1){
$var1++;
echo "In Exam:" . $var1 . "<br />";
}

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


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

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

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

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

<?php
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 . "<br />";
}
}
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

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板