How to pass object as function parameter in PHP?

WBOY
Release: 2024-04-11 11:18:02
Original
757 people have browsed it

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.

如何在 PHP 中传递对象作为函数参数?

How to pass objects as function parameters in PHP?

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 Object Reference

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"
Copy after login

Passing the object by value

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"
Copy after login

Practical Case

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"
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!