Bird
Raised Fist0
PHPprogramming~15 mins

Parent keyword behavior in PHP - Deep Dive

Choose your learning style10 modes available
Overview - Parent keyword behavior
What is it?
In PHP, the parent keyword is used inside a child class to access methods or properties from its parent class. It allows the child class to call or extend the behavior of the parent class, especially when overriding methods. This keyword helps maintain and reuse code by linking child and parent classes clearly.
Why it matters
Without the parent keyword, child classes would have no direct way to use or extend the functionality of their parent classes. This would lead to code duplication and harder maintenance. The parent keyword solves this by enabling clean inheritance and method reuse, making programs easier to build and update.
Where it fits
Before learning about the parent keyword, you should understand basic class and object concepts in PHP, including inheritance. After mastering parent keyword behavior, you can explore advanced object-oriented programming topics like traits, interfaces, and design patterns.
Mental Model
Core Idea
The parent keyword lets a child class reach up to its parent class to reuse or extend its methods and properties.
Think of it like...
Imagine a child asking their parent for advice before making a decision. The child can listen to the parent's wisdom and then add their own ideas.
┌─────────────┐       ┌─────────────┐
│ ParentClass │──────▶│ ChildClass  │
└─────────────┘       └─────────────┘
       ▲                      │
       │                      │
       │                 parent::method()
       │                      │
       └──────────────────────┘
Build-Up - 6 Steps
1
FoundationBasic class inheritance in PHP
🤔
Concept: Learn how a child class inherits methods and properties from a parent class.
greet(); ?>
Result
Hello from Parent
Understanding inheritance is essential because the parent keyword only works when a child class extends a parent class.
2
FoundationOverriding methods in child class
🤔
Concept: Child classes can replace parent methods by defining their own with the same name.
greet(); ?>
Result
Hello from Child
Overriding lets child classes customize behavior, but sometimes you still want to use the parent's original method.
3
IntermediateUsing parent keyword to call parent method
🤔Before reading on: do you think calling parent::method() inside a child method replaces or extends the parent's method? Commit to your answer.
Concept: The parent keyword calls the parent's version of a method even if the child overrides it.
greet(); ?>
Result
Hello from Parent and Child
Using parent::method() allows the child to extend the parent's behavior instead of completely replacing it.
4
IntermediateAccessing parent constructor with parent keyword
🤔
Concept: Child classes can call the parent's constructor to initialize inherited properties properly.
name = $name; } } class ChildClass extends ParentClass { private $age; public function __construct($name, $age) { parent::__construct($name); $this->age = $age; } public function info() { return $this->name . ' is ' . $this->age . ' years old.'; } } $child = new ChildClass('Alice', 30); echo $child->info(); ?>
Result
Alice is 30 years old.
Calling parent::__construct() ensures the parent class sets up its part of the object correctly.
5
AdvancedUsing parent keyword with static methods
🤔Before reading on: do you think parent:: can be used to call static methods from the parent class? Commit to yes or no.
Concept: The parent keyword can call static methods from the parent class inside child classes.
Result
Hello from Parent static method and Child static method
parent:: works with static methods, enabling reuse and extension of static behavior.
6
ExpertLimitations and edge cases of parent keyword
🤔Before reading on: do you think parent:: can be used outside a class context or in traits? Commit to your answer.
Concept: parent keyword only works inside class methods and cannot be used outside class context or in traits without a parent class.
greet(); ?>
Result
Hello from Parent
Knowing where parent:: can be used prevents runtime errors and clarifies inheritance boundaries.
Under the Hood
When PHP encounters parent:: inside a child class method, it looks up the inheritance chain to find the parent class's method or property. It then calls that method or accesses that property in the context of the current object. This allows the child to reuse or extend the parent's implementation without duplicating code.
Why designed this way?
The parent keyword was designed to provide a clear, explicit way to access overridden methods or properties in the parent class. This avoids ambiguity and accidental infinite recursion that could happen if a child method called itself. It also supports clean code reuse and easier maintenance.
┌─────────────┐
│ ChildClass  │
│ ┌─────────┐ │
│ │greet()  │ │
│ │ calls  │ │
│ │parent:: │ │
│ │greet()  │ │
│ └─────────┘ │
└─────┬───────┘
      │
      ▼
┌─────────────┐
│ ParentClass │
│ greet()     │
└─────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does parent:: call the parent's method even if the child method does not override it? Commit to yes or no.
Common Belief:parent:: can be used to call a parent's method even if the child class does not override that method.
Tap to reveal reality
Reality:parent:: can only be used inside a child method that overrides the parent's method; otherwise, it causes an error.
Why it matters:Using parent:: outside an overriding method leads to fatal errors, breaking the program.
Quick: Can parent:: access private properties or methods of the parent class? Commit to yes or no.
Common Belief:parent:: can access all properties and methods of the parent class, including private ones.
Tap to reveal reality
Reality:parent:: cannot access private members of the parent class; only protected and public members are accessible.
Why it matters:Assuming access to private members causes access errors and security issues.
Quick: Does parent:: always refer to the immediate parent class? Commit to yes or no.
Common Belief:parent:: always refers to the immediate parent class in the inheritance chain.
Tap to reveal reality
Reality:parent:: refers to the immediate parent class, but in complex inheritance with multiple levels, it does not skip classes or refer to grandparents directly.
Why it matters:Misunderstanding this can cause confusion when multiple inheritance levels exist and expected methods are not called.
Quick: Can parent:: be used outside class methods, like in global functions? Commit to yes or no.
Common Belief:parent:: can be used anywhere in PHP code to access parent class methods.
Tap to reveal reality
Reality:parent:: can only be used inside class methods; using it outside causes syntax errors.
Why it matters:Trying to use parent:: outside class context leads to syntax errors and program failure.
Expert Zone
1
parent:: calls are resolved at compile time, so they cannot be used dynamically with variable method names.
2
In traits, parent:: calls refer to the class using the trait's parent, which can cause unexpected behavior if the trait is used in different inheritance contexts.
3
Using parent:: in constructors is crucial for proper initialization but forgetting it can cause subtle bugs with uninitialized properties.
When NOT to use
Avoid using parent:: when you want to completely replace the parent's behavior instead of extending it. Also, do not use parent:: in classes without a parent, or outside class methods. For code reuse without inheritance, consider composition or traits instead.
Production Patterns
In real-world PHP applications, parent:: is commonly used in overridden methods to extend functionality, especially in constructors, event handlers, and framework lifecycle methods. It helps maintain clean inheritance hierarchies and avoid code duplication.
Connections
Method overriding in object-oriented programming
parent keyword builds on method overriding by allowing access to the overridden method.
Understanding parent keyword clarifies how child classes can extend rather than replace parent behavior.
Call stack in programming languages
parent:: calls affect the call stack by explicitly invoking a method higher in the inheritance chain.
Knowing how parent:: works helps understand call stack flow and prevents infinite recursion.
Inheritance in biology
parent keyword conceptually mirrors biological inheritance where offspring inherit traits from parents but can add their own variations.
Seeing inheritance in programming like biological inheritance helps grasp why child classes reuse and extend parent features.
Common Pitfalls
#1Calling parent::method() outside an overriding method
Wrong approach:sayHello(); ?>
Correct approach:greet(); } } $child = new ChildClass(); echo $child->sayHello(); ?>
Root cause:parent:: can only be used inside a method that overrides the parent's method; using it elsewhere causes errors.
#2Trying to access private parent properties with parent::
Wrong approach:secret; } } class ChildClass extends ParentClass { public function reveal() { return parent::$secret; // Error: private property } } $child = new ChildClass(); echo $child->reveal(); ?>
Correct approach:secret; } } class ChildClass extends ParentClass { public function reveal() { return parent::getSecret(); } } $child = new ChildClass(); echo $child->reveal(); ?>
Root cause:Private properties are not accessible outside their own class; parent:: cannot bypass visibility rules.
#3Forgetting to call parent constructor in child constructor
Wrong approach:name = $name; } } class ChildClass extends ParentClass { private $age; public function __construct($name, $age) { $this->age = $age; } public function info() { return $this->name . ' is ' . $this->age . ' years old.'; } } $child = new ChildClass('Alice', 30); echo $child->info(); ?>
Correct approach:name = $name; } } class ChildClass extends ParentClass { private $age; public function __construct($name, $age) { parent::__construct($name); $this->age = $age; } public function info() { return $this->name . ' is ' . $this->age . ' years old.'; } } $child = new ChildClass('Alice', 30); echo $child->info(); ?>
Root cause:Not calling parent::__construct() leaves parent properties uninitialized, causing bugs.
Key Takeaways
The parent keyword in PHP allows child classes to access and extend methods or properties from their parent classes.
It is essential to use parent:: only inside overriding methods to avoid errors and maintain clear inheritance behavior.
Calling parent::__construct() in child constructors ensures proper initialization of inherited properties.
parent:: works with both instance and static methods but respects visibility rules like private and protected.
Understanding parent keyword behavior helps write cleaner, reusable, and maintainable object-oriented PHP code.

Practice

(1/5)
1. What does the parent keyword do in PHP classes?
easy
A. It renames the parent class.
B. It creates a new instance of the parent class.
C. It deletes the parent class methods from the child class.
D. It allows a child class to access methods or properties from its parent class.

Solution

  1. Step 1: Understand the role of parent keyword

    The parent keyword in PHP is used inside a child class to refer to its parent class.
  2. Step 2: Identify what parent allows

    It allows the child class to call or extend methods or properties defined in the parent class.
  3. Final Answer:

    It allows a child class to access methods or properties from its parent class. -> Option D
  4. Quick Check:

    parent accesses parent methods/properties [OK]
Hint: Remember: parent calls parent class features [OK]
Common Mistakes:
  • Thinking parent creates new objects
  • Confusing parent with $this
  • Believing parent deletes methods
2. Which of the following is the correct syntax to call a parent class method named show inside a child class method?
easy
A. parent.show();
B. parent->show();
C. parent::show();
D. parent:show();

Solution

  1. Step 1: Recall PHP syntax for calling parent methods

    In PHP, to call a parent class method inside a child, use the scope resolution operator :: with parent.
  2. Step 2: Match the correct syntax

    The correct syntax is parent::methodName();, so for method show, it is parent::show();.
  3. Final Answer:

    parent::show(); -> Option C
  4. Quick Check:

    Use :: with parent to call methods [OK]
Hint: Use double colon (::) to call parent methods [OK]
Common Mistakes:
  • Using arrow (->) instead of double colon (::)
  • Using dot (.) operator which is for strings
  • Using single colon (:) which is invalid syntax
3. What will be the output of this PHP code?
class A {
  public function greet() {
    return "Hello from A";
  }
}

class B extends A {
  public function greet() {
    return parent::greet() . " and B";
  }
}

$b = new B();
echo $b->greet();
medium
A. Hello from A
B. Hello from A and B
C. Hello from B
D. Error: Cannot call parent method

Solution

  1. Step 1: Understand method overriding and parent call

    Class B overrides greet() but calls parent::greet() which returns "Hello from A".
  2. Step 2: Concatenate parent result with " and B"

    The child method returns the parent's string plus " and B", so the full string is "Hello from A and B".
  3. Final Answer:

    Hello from A and B -> Option B
  4. Quick Check:

    parent::greet() + " and B" = "Hello from A and B" [OK]
Hint: parent::method() returns parent's output, can concatenate [OK]
Common Mistakes:
  • Ignoring parent:: call and expecting only child's string
  • Thinking it causes an error
  • Confusing output with only parent's or only child's string
4. Identify the error in this PHP code:
class ParentClass {
  public function sayHi() {
    echo "Hi from parent";
  }
}

class ChildClass extends ParentClass {
  public function sayHi() {
    parent.sayHi();
    echo " and child";
  }
}

$obj = new ChildClass();
$obj->sayHi();
medium
A. Using dot (.) instead of scope resolution (::) to call parent method
B. Missing parentheses after method name
C. Child class cannot override parent methods
D. Parent class method is private

Solution

  1. Step 1: Check how parent method is called

    The code uses parent.sayHi(); which is invalid syntax in PHP.
  2. Step 2: Correct syntax uses scope resolution operator

    It should be parent::sayHi(); to call the parent method inside child.
  3. Final Answer:

    Using dot (.) instead of scope resolution (::) to call parent method -> Option A
  4. Quick Check:

    Use parent::method(), not parent.method() [OK]
Hint: Use ::, not . to call parent methods [OK]
Common Mistakes:
  • Using dot (.) operator for method calls
  • Forgetting parentheses after method name
  • Assuming private methods can be called by child
5. Given these classes, what will be the output?
class Base {
  protected function message() {
    return "Base message";
  }
}

class Derived extends Base {
  public function message() {
    return parent::message() . " extended";
  }
}

class MoreDerived extends Derived {
  public function message() {
    return parent::message() . " and more";
  }
}

$obj = new MoreDerived();
echo $obj->message();
hard
A. Base message extended and more
B. Base message and more
C. Error: Cannot access protected method
D. Base message extended

Solution

  1. Step 1: Trace method calls through inheritance

    MoreDerived::message() calls parent::message() which is Derived::message().
  2. Step 2: Derived::message() calls Base::message()

    Derived calls parent::message() which is Base::message() returning "Base message" and appends " extended".
  3. Step 3: Combine all returned strings

    So Derived returns "Base message extended" and MoreDerived appends " and more" resulting in "Base message extended and more".
  4. Final Answer:

    Base message extended and more -> Option A
  5. Quick Check:

    Chained parent calls build full string [OK]
Hint: Each parent:: call adds to string stepwise [OK]
Common Mistakes:
  • Expecting error due to protected method (allowed in child)
  • Ignoring chained parent calls
  • Assuming only base message prints
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard