The parent:: Keyword
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 22 of 91.
When a child class inherits from a parent, sometimes you need to access the parent's methods or properties directly. The parent:: keyword lets you call the parent class's implementation from within the child class.
This is especially useful in constructors when the child needs to initialize the parent's properties while also setting up its own:
<?php
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
class Dog extends Animal {
public $breed;
public function __construct($name, $breed) {
parent::__construct($name);
$this->breed = $breed;
}
public function describe() {
return "$this->name is a $this->breed";
}
}
$dog = new Dog("Max", "Labrador");
echo $dog->describe();
Output:
Max is a LabradorBy calling parent::__construct($name), the child class reuses the parent's initialization logic instead of duplicating it. Without this call, the $name property would never be set.
You can use parent:: to call any parent method, not just constructors. This becomes particularly important when you want to extend a method's behavior rather than completely replace it.
Key Point: The parent:: keyword provides a way to access the parent class's implementation. It's essential for proper constructor chaining and for building upon inherited functionality rather than rewriting it.
Challenge
EasyLet's build a product catalog system that demonstrates how child classes can extend parent functionality using the parent:: keyword to properly chain constructors and build upon inherited methods.
You'll organize your code across three files:
Product.php— Define aProductclass that serves as the base for all products. It should have public properties$nameand$price. The constructor accepts a name and price, setting both properties. Include agetDetails()method that returns"[name]: $[price]".ElectronicProduct.php— Define anElectronicProductclass that extendsProduct. Include the Product file at the top. This class adds a$warrantyproperty (in months). The constructor should accept name, price, and warranty — useparent::__construct()to initialize the name and price through the parent, then set the warranty yourself. Create agetDetails()method that builds upon the parent's implementation: callparent::getDetails()and append" (Warranty: [warranty] months)"to it.main.php— Include the ElectronicProduct file. You'll receive three inputs: the product name, price (as a string to convert to a float), and warranty period (as a string to convert to an integer). Create anElectronicProductwith these values and print the result of callinggetDetails().
This challenge shows the real power of parent:: — not just for constructor chaining, but also for extending method behavior. Your ElectronicProduct reuses the parent's formatting logic and adds its own details on top, avoiding code duplication while creating richer output.
Cheat sheet
The parent:: keyword allows a child class to access methods and properties from its parent class.
Use parent::__construct() to call the parent's constructor from the child class:
<?php
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
class Dog extends Animal {
public $breed;
public function __construct($name, $breed) {
parent::__construct($name);
$this->breed = $breed;
}
}
You can also use parent:: to call any parent method and extend its behavior:
<?php
class Animal {
public function describe() {
return "This is an animal";
}
}
class Dog extends Animal {
public function describe() {
return parent::describe() . " and it's a dog";
}
}
This approach allows child classes to reuse parent logic instead of duplicating code, enabling proper constructor chaining and method extension.
Try it yourself
<?php
require_once 'ElectronicProduct.php';
// Read inputs
$name = trim(fgets(STDIN));
$price = floatval(trim(fgets(STDIN)));
$warranty = intval(trim(fgets(STDIN)));
// TODO: Create an ElectronicProduct with the input values
// and print the result of calling getDetails()
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern