How can encapsulation and inheritance be used effectively in PHP classes to handle data manipulation?
Encapsulation and inheritance can be used effectively in PHP classes to handle data manipulation by creating parent classes that contain common data and methods, and then extending these classes to create more specialized child classes that inherit the properties and methods of the parent class. Encapsulation ensures that data is kept private within the class and only accessible through getter and setter methods, while inheritance allows child classes to reuse and extend the functionality of the parent class.
<?php
class Person {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
}
class Employee extends Person {
private $employeeId;
public function __construct($name, $employeeId) {
parent::__construct($name);
$this->employeeId = $employeeId;
}
public function getEmployeeId() {
return $this->employeeId;
}
public function setEmployeeId($employeeId) {
$this->employeeId = $employeeId;
}
}
$employee = new Employee("John Doe", 12345);
echo $employee->getName(); // Output: John Doe
echo $employee->getEmployeeId(); // Output: 12345
?>
Related Questions
- Can a session ID be reassigned to a different user in PHP, and how can this impact system security?
- In the context of PHP arrays, how can the correct indexing and numbering be maintained when outputting multiple elements using array_slice?
- What best practices should be followed when integrating Flash games into a PHP-based website?