Arguments between php functions pass of values pass and reference passes
- 2020-09-28 08:49:34
- OfStack
php: Parameter passing between functions
1. The value
-------------------------------------------------------------------------------
Output results:
1
In Exam: 2
1
-------------------------------------------------------------------------------
2. Reference passing
-------------------------------------------------------------------------------
Output results:
1
In Exam: 2
2
-------------------------------------------------------------------------------
3. Optional parameters
Output results:
Total Price: 125
Total Price: 100
-------------------------------------------------------------------------------
4. If you pass in an object, you can change the value of that object
(The variable $obj actually records the handle to this object, passing in $obj as a parameter, which allows you to manipulate the original object.)
-------------------------------------------------------------------------------
Output results:
Mr. zhan 12 male
Mr. zhan 13 male
Mr. zhan 14 male
1. The value
<?php
function exam($var1){
$var1++ ;
echo "In Exam:" . $var1 . "<br />";
}
$var1 = 1;
echo $var1 . "<br />";
exam($var1);
echo $var1 . "<br />";
?>
-------------------------------------------------------------------------------
Output results:
1
In Exam: 2
1
-------------------------------------------------------------------------------
2. Reference passing
<?php
function exam( &$var1){
$var1++ ;
echo "In Exam:" . $var1 . "<br />";
}
$var1 = 1;
echo $var1 . "<br />";
exam($var1);
echo $var1 . "<br />";
?>
-------------------------------------------------------------------------------
Output results:
1
In Exam: 2
2
-------------------------------------------------------------------------------
3. Optional parameters
function values($price, $tax=""){
$price += $prive * $tax;
echo "Total Price:" . $price . "<br />";
}
values(100, 0.25);
values(100);
Output results:
Total Price: 125
Total Price: 100
-------------------------------------------------------------------------------
4. If you pass in an object, you can change the value of that object
(The variable $obj actually records the handle to this object, passing in $obj as a parameter, which allows you to manipulate the original object.)
<?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();
?>
-------------------------------------------------------------------------------
Output results:
Mr. zhan 12 male
Mr. zhan 13 male
Mr. zhan 14 male