How can the concept of inheritance be applied in PHP classes, specifically when accessing parent objects?
When working with inheritance in PHP classes, you may need to access properties or methods from a parent class within a child class. This can be achieved using the `parent` keyword followed by `::` to access static properties or methods, or `->` to access non-static properties or methods of the parent class.
class ParentClass {
protected $parentProperty = 'Parent property';
protected function parentMethod() {
return 'Parent method';
}
}
class ChildClass extends ParentClass {
public function getChildData() {
$parentProperty = $this->parentProperty;
$parentMethod = parent::parentMethod();
return [$parentProperty, $parentMethod];
}
}
$child = new ChildClass();
$data = $child->getChildData();
print_r($data);
Keywords
Related Questions
- How can PHP be used to streamline manual tasks like copying and pasting data?
- Why is it important to close all function declarations and control structures in PHP code properly?
- In what scenarios would it be more efficient to use Ajax for passing geolocation variables to PHP compared to traditional methods?