Php Inheritance And Access Modifiers Complete Guide
Understanding the Core Concepts of PHP Inheritance and Access Modifiers
PHP Inheritance and Access Modifiers
Inheritance Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a new class, called a derived or child class, to inherit properties and methods from an existing class, referred to as a parent or base class. This promotes code reusability and establishes a hierarchical relationship between classes.
Syntax for Inheritance
To create a child class that inherits from a parent class, use the extends
keyword:
class ParentClass {
// Properties and methods
}
class ChildClass extends ParentClass {
// Properties and methods
}
In this example, ChildClass
inherits everything from ParentClass
.
Overriding Methods and Properties A child class can override a method defined in its parent class by simply defining a method with the same name. However, overriding properties directly isn't supported in PHP as it might lead to ambiguity.
class ParentClass {
protected $message = 'Hello from parent!';
public function sayHello() {
echo $this->message;
}
}
class ChildClass extends ParentClass {
protected $message = 'Hello from child!'; // Property doesn't get overridden
public function sayHello() { // Method gets overridden
echo $this->message;
}
}
When you call $child->sayHello();
, it will output 'Hello from child!'
.
Accessing Parent Methods in Child Class
A child class can access a parent method using the parent::
keyword.
class ChildClass extends ParentClass {
public function sayHello() {
parent::sayHello(); // Call parent method
echo ' And hello from child!';
}
}
Polymorphism Polymorphism occurs when a child class provides a specific implementation of a method that is already provided by one of its parent classes.
interface Shape {
public function draw();
}
class Circle implements Shape {
public function draw() {
echo 'Drawing Circle';
}
}
class Square implements Shape {
public function draw() {
echo 'Drawing Square';
}
}
In this case, both Circle
and Square
provide their own implementations of the draw()
method.
Access Modifiers
Access modifiers control the visibility and accessibility of class properties and methods. There are three primary access modifiers in PHP:
1. Public Public properties and methods can be accessed from anywhere, both inside and outside the class, by any other classes.
class MyClass {
public $publicProperty = 'I am a public property';
public function publicMethod() {
echo 'I am a public method';
}
}
2. Protected Protected members can only be accessed within the class itself and by inheriting classes.
class MyParentClass {
protected $protectedProperty = 'I am a protected property';
protected function protectedMethod() {
echo 'I am a protected method';
}
}
class MyChildClass extends MyParentClass {
public function accessProtectedMembers() {
echo $this->protectedProperty; // Can access protected property
$this->protectedMethod(); // Can call protected method
}
}
3. Private Private members can only be accessed within the class where they are declared. They cannot be accessed or overridden by inheriting classes.
class MyParentClass {
private $privateProperty = 'I am a private property';
private function privateMethod() {
echo 'I am a private method';
}
public function getPrivateMembers() {
echo $this->privateProperty;
$this->privateMethod();
}
}
class MyChildClass extends MyParentClass {
public function accessPrivateMembers() {
// The following lines would result in errors
// echo $this->privateProperty;
// $this->privateMethod();
}
}
Static Members
Static methods and properties belong to the class rather than instances of the class. You can access static members using the self::
keyword within the class, and ClassName::
from outside.
class MyClass {
public static $staticProperty = 'Static property';
public static function staticMethod() {
echo 'Static method';
}
}
echo MyClass::$staticProperty; // Access static property
MyClass::staticMethod(); // Call static method from outside
Constructor and Destructor
- Constructors (
__construct()
) and destructors (__destruct()
) can also be inherited and overridden in PHP. - If a constructor is not defined in a child class, PHP automatically calls the constructor from the parent class.
Abstract Classes Abstract classes cannot be instantiated on their own and are meant to be inherited. They can contain abstract methods, which must be implemented by any child class.
abstract class AbstractClass {
abstract public function calculateArea();
public function nonAbstractMethod() {
echo 'Non-abstract method';
}
}
class ConcreteClass extends AbstractClass {
public function calculateArea() {
// Implement abstract method
echo 'Area calculation';
}
}
Final Keyword
The final
keyword can be used to prevent a class or a method from being overridden in child classes.
final class FinalClass {
final public function finalMethod() {
echo 'This method cannot be overridden';
}
}
// The following would cause a fatal error
// class AnotherClass extends FinalClass {} // This will fail
// class AnotherClass {
// final public function anotherMethod() {} // This will succeed but
// }
// class YetAnotherClass extends AnotherClass {
// public function anotherMethod() {} // Overriding here will fail
// }
Visibility Table Here's a table summarizing visibility rules:
| Access Modifier | Inside Class | Inside Subclass | Outside Class | |-----------------|--------------|-----------------|---------------| | Public | Yes | Yes | Yes | | Protected | Yes | Yes | No | | Private | Yes | No | No |
Online Code run
Step-by-Step Guide: How to Implement PHP Inheritance and Access Modifiers
1. Basic Inheritance
Concept: Inheritance allows a class to inherit properties and methods from another class.
Example:
<?php
// Base class (parent class)
class Animal {
public $name;
public $species;
function __construct($name, $species) {
$this->name = $name;
$this->species = $species;
}
function makeSound() {
echo "Some generic sound\n";
}
}
// Derived class (child class) inherits from Animal
class Dog extends Animal {
function makeSound() {
echo "Woof woof\n";
}
}
// Create an instance of Dog
$myDog = new Dog("Buddy", "Canine");
echo $myDog->name . " is a " . $myDog->species . ".\n";
$myDog->makeSound();
// Output:
// Buddy is a Canine.
// Woof woof
?>
2. Access Modifiers
Concept: Access Modifiers control the visibility of methods and properties within a class. There are three types: public
, protected
, and private
.
public
: The method or property can be accessed from anywhere.protected
: The method or property can be accessed within its own class and by inheriting classes.private
: The method or property can only be accessed within its own class.
Example:
<?php
class Vehicle {
// Public property
public $type;
// Protected property
protected $make;
// Private property
private $model;
function __construct($type, $make, $model) {
$this->type = $type;
$this->make = $make;
$this->model = $model;
}
// Public method
public function getVehicleInfo() {
return "This is a {$this->type} made by {$this->make}.";
}
// Protected method
protected function getPrivateModel() {
return $this->model;
}
// Private method
private function getVehicleDetails() {
return "Type: {$this->type}, Make: {$this->make}, Model: {$this->model}";
}
}
// Subclass that inherits from Vehicle
class Car extends Vehicle {
public function getCarDetails() {
// Can access public and protected members
return $this->getVehicleInfo() . " Model: " . $this->getPrivateModel();
}
}
// Create an instance of Car
$myCar = new Car("Sedan", "Toyota", "Corolla");
// Access public member
echo $myCar->type . "\n"; // Output: Sedan
// Access public method
echo $myCar->getVehicleInfo() . "\n"; // Output: This is a Sedan made by Toyota.
// Access protected method through subclass method
echo $myCar->getCarDetails() . "\n"; // Output: This is a Sedan made by Toyota. Model: Corolla
// Uncommenting the following line will cause a fatal error because $make is protected
// echo $myCar->make . "\n";
// Uncommenting the following line will cause a fatal error because model is private
// echo $myCar->getPrivateModel() . "\n";
?>
3. Overriding Methods with Access Modifiers
Concept: When a method in a child class has the same name as a method in the parent class, it overrides the parent class's method. Access modifiers can affect method overriding rules.
Example:
Top 10 Interview Questions & Answers on PHP Inheritance and Access Modifiers
1. What is Inheritance in PHP?
Inheritance is a mechanism where a class can inherit properties and methods from another class, referred to as the parent or base class. This promotes code reusability and establishes a hierarchical relationship between classes.
Example:
class Animal {
public function eat() {
echo "Eating";
}
}
class Dog extends Animal {
// Dog class inherits 'eat' method from Animal class
}
$dog = new Dog();
$dog->eat(); // Outputs: Eating
2. How can multiple inheritance be achieved in PHP?
PHP does not support multiple inheritance, meaning a class cannot extend more than one class directly. However, you can achieve similar functionality using interfaces.
Example:
interface Flyable {
public function fly();
}
interface Swimmable {
public function swim();
}
class Duck implements Flyable, Swimmable {
public function fly() {
echo "Flying";
}
public function swim() {
echo "Swimming";
}
}
3. What are the different types of access modifiers in PHP?
PHP provides three key access modifiers:
- public: The property or method can be accessed from anywhere, both inside and outside the class.
- protected: The property or method can only be accessed within the class itself and by inheriting child classes.
- private: The property or method can only be accessed within the class itself. It is not available to child classes nor outside the class.
Example:
class Vehicle {
public $color;
protected $engineType;
private $chassisNumber;
public function getDetails() {
return [
'color' => $this->color,
'engineType' => $this->engineType,
'chassisNumber' => $this->chassisNumber
];
}
protected function setEngineType($type) {
$this->engineType = $type;
}
private function setChassisNumber($number) {
$this->chassisNumber = $number;
}
}
class Car extends Vehicle {
public function __construct($color, $engineType, $chassisNumber){
$this->color = $color;
$this->setEngineType($engineType);
#$this->setChassisNumber($chassisNumber); // Results in a Fatal Error
}
}
4. Can a child class override a method inherited from its parent class?
Yes, a child class can override (or redefine) a method that is inherited from its parent class. The overriding method must have the same name and parameters.
Example:
class ParentClass {
public function greet() {
echo "Hello from Parent!";
}
}
class ChildClass extends ParentClass {
public function greet() { // Overriding 'greet' method
echo "Hello from Child!";
}
}
$childObj = new ChildClass();
$childObj->greet(); // Outputs: Hello from Child!
5. Explain the concept of final keyword in PHP inheritance.
The final
keyword prevents a class from being extended and a method from being overridden in any descendant class.
Example:
final class BaseClass {
final public function show() {
echo "This is a final method.";
}
}
// class DerivedClass extends BaseClass {} Results in a Fatal Error: Class DerivedClass may not inherit from final class (BaseClass)
6. What is visibility of properties and methods in PHP?
Visibility refers to the scope in which methods and properties are accessible. This determines whether they can be accessed from outside the class, from child classes, or only within the class itself. It is controlled by the access modifiers (public, protected, private).
Example:
Already provided in question 3.
7. How does PHP handle constructor inheritance when extending a class?
In PHP, constructors are not inherited by child classes, but a child class can call the parent class's constructor using the parent::__construct()
syntax if required.
Example:
class Person {
public $name;
public function __construct($name){
$this->name = $name;
}
}
class Employee extends Person {
public $id;
public function __construct($name, $id){
parent::__construct($name); // Calling parent constructor
$this->id = $id;
}
}
$employee = new Employee("John Doe", 12345);
echo $employee->name; // Outputs: John Doe
8. How can you access a private method from a parent class in a child class?
A private method is not accessible directly from a child class. If you need to use its functionality, you should either make it protected or create a public method in the parent class that encapsulates this functionality and then call it from the child class.
Example: Correct approach:
class ParentClass {
private function hiddenMethod(){
echo "Private Method.";
}
public function visibleMethod(){
$this->hiddenMethod();
}
}
class ChildClass extends ParentClass {
public function callHidden() {
$this->visibleMethod(); // Correctly accessing private method via public
}
}
$obj = new ChildClass();
$obj->callHidden(); // Outputs: Private Method.
9. Explain PHP's magic method __call to handle undefined method calls.
PHP provides the magic method __call()
, which is automatically invoked when an undefined method is called in an object context. __call()
is useful for creating flexible APIs that can handle method calls dynamically at runtime.
Example:
class MyClass {
public function __call($method, $args){
if ($method == 'customMethod') {
echo "Calling customMethod with arguments: " . implode(', ', $args);
} else {
echo "Method '$method' with arguments " . implode(', ', $args) ." does not exist.";
}
}
}
$obj = new MyClass();
$obj->customMethod('Hello', 'World'); // Outputs: Calling customMethod with arguments: Hello, World
$obj->nonexistentMethod('foo', 'bar'); // Outputs: Method 'nonexistentMethod' with arguments foo, bar does not exist.
10. What is the significance of accessing modifiers when implementing inheritance?
Access modifiers control the visibility of class members, which is crucial in designing secure and manageable class hierarchies. Proper use enhances encapsulation, protecting internal class state and ensuring that only intended interactions occur between classes and their users, thereby supporting good software design principles like SOLID.
Summary Benefits:
- Helps in maintaining data integrity.
- Enables code reuse and avoids duplication.
- Facilitates polymorphism, allowing methods to do different things based on the object that calls them.
- Simplifies maintenance and extension of code by enforcing clear boundaries and responsibilities.
Login to post a comment.