0
0
PHPprogramming~5 mins

Parent keyword behavior in PHP

Choose your learning style9 modes available
Introduction

The parent keyword helps you use or change things from a parent class inside a child class.

When you want to call a method from the parent class inside a child class method.
When you want to access a property or method that is defined in the parent class.
When you want to extend or modify the behavior of a parent class method without rewriting it completely.
When you want to call the parent constructor from a child class constructor.
Syntax
PHP
parent::methodName();
parent::$propertyName;
parent::__construct();

parent:: is used to access methods or properties from the parent class.

You use it inside a child class to refer to the parent class.

Examples
This example shows how the child class Dog calls the parent class Animal method speak() using parent::speak() before adding its own message.
PHP
<?php
class Animal {
    public function speak() {
        echo "Animal sound\n";
    }
}

class Dog extends Animal {
    public function speak() {
        parent::speak();
        echo "Bark!\n";
    }
}

$dog = new Dog();
$dog->speak();
This example shows how the child class Car calls the parent constructor using parent::__construct() to keep the parent setup and add its own.
PHP
<?php
class Vehicle {
    public function __construct() {
        echo "Vehicle created\n";
    }
}

class Car extends Vehicle {
    public function __construct() {
        parent::__construct();
        echo "Car created\n";
    }
}

$car = new Car();
Sample Program

This program shows a Student class that uses parent::greet() to call the greet method from the Person parent class, adding its own message first.

PHP
<?php
class Person {
    public function greet() {
        echo "Hello from Person\n";
    }
}

class Student extends Person {
    public function greet() {
        echo "Student says: ";
        parent::greet();
    }
}

$student = new Student();
$student->greet();
OutputSuccess
Important Notes

You can only use parent:: inside a class that extends another class.

If the parent method or property does not exist, PHP will give an error.

Summary

parent lets child classes use or extend parent class methods or properties.

Use parent::methodName() to call a parent method inside a child method.

It helps avoid repeating code and keeps your program organized.