Home > Article > Backend Development > How to pass object as function parameter in PHP?
In PHP, objects can be passed to functions by reference or value. Passing a reference allows the function to modify the original object, and passing a value creates a copy of the original object. In the actual case, the employee management system uses object reference passing to allow functions to modify the salary of the original employee object.
In PHP, objects can be passed to functions by reference or value. Either way, the function will obtain a reference or copy of the object.
Passing an object by reference allows a function to modify the original object. To do this, pass the object using the &
notation:
class Person { public $name; public function __construct($name) { $this->name = $name; } } function changeName(&$person) { $person->name = "John Doe"; } $person = new Person("Jane Doe"); changeName($person); echo $person->name; // 输出 "John Doe"
Passing the object by value creates a copy of the original object. This allows functions to modify the copy without affecting the original object:
class Person { public $name; public function __construct($name) { $this->name = $name; } } function changeName($person) { $person->name = "John Doe"; } $person = new Person("Jane Doe"); changeName($person); echo $person->name; // 输出 "Jane Doe"
Employee Management System
Suppose we have an employee management system , one of the functions needs to access employee information for modification.
class Employee { public $name; public $salary; } function updateSalary(Employee $employee, $newSalary) { $employee->salary = $newSalary; } $employee = new Employee(); $employee->name = "Jane Doe"; $employee->salary = 1000; updateSalary($employee, 1200); echo $employee->salary; // 输出 "1200"
In this case, passing the $employee
object using an object reference enables the updateSalary()
function to modify the salary of the original object.
The above is the detailed content of How to pass object as function parameter in PHP?. For more information, please follow other related articles on the PHP Chinese website!