0
0
PHPprogramming~10 mins

Extending classes in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Extending classes
Define Parent Class
Define Child Class extends Parent
Create Child Object
Child inherits Parent methods/props
Call methods on Child
If method overridden, Child's version runs
Program Ends
This flow shows how a child class inherits from a parent class, can override methods, and how objects use these methods.
Execution Sample
PHP
<?php
class Animal {
  public function speak() {
    echo "Animal sound\n";
  }
}

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

$dog = new Dog();
$dog->speak();
?>
This code defines a parent class Animal and a child class Dog that overrides the speak method. It creates a Dog object and calls speak.
Execution Table
StepActionClass/MethodOutputNotes
1Define class AnimalAnimalParent class created with speak() method
2Define class Dog extends AnimalDogChild class created, inherits Animal
3Create object $dog = new Dog()Dog::__constructDog object created
4Call $dog->speak()Dog::speakBark! Dog's speak() overrides Animal's
5Program endsExecution complete
💡 Program ends after calling Dog's speak method which outputs 'Bark!'
Variable Tracker
VariableStartAfter CreationFinal
$dogundefinedobject of Dogobject of Dog
Key Moments - 2 Insights
Why does $dog->speak() print 'Bark!' and not 'Animal sound'?
Because Dog class overrides the speak() method from Animal. See execution_table step 4 where Dog::speak runs instead of Animal::speak.
Does Dog class have access to Animal's methods if not overridden?
Yes, Dog inherits all methods from Animal. If Dog does not override a method, calling it on Dog object uses Animal's version.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 4?
AAnimal sound
BNo output
CBark!
DError
💡 Hint
Check the Output column in execution_table row with Step 4
At which step is the Dog object created?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the Action column for object creation in execution_table
If Dog did not override speak(), what would $dog->speak() output?
ABark!
BAnimal sound
CNo output
DError
💡 Hint
Refer to key_moments about method inheritance and overriding
Concept Snapshot
Extending classes in PHP:
class Child extends Parent {
  // Child inherits Parent's methods and properties
  // Can override methods by redefining them
}
Create child object: $obj = new Child();
Calling methods uses Child's version if overridden, else Parent's.
Full Transcript
This example shows how PHP classes can extend other classes. The parent class Animal has a method speak() that prints 'Animal sound'. The child class Dog extends Animal and overrides speak() to print 'Bark!'. When we create a Dog object and call speak(), it runs Dog's version, printing 'Bark!'. This demonstrates inheritance and method overriding in PHP classes.