Calling extended class function from parent class

18,394

Solution 1

Yes, you can call a method in the extending class.

<?php
class a 
{
    public function a1 ()
    {
        $this->b1();    
    }

    protected function b1()
    {
        echo 'This is in the a class<br />';
    }
}

class b extends a 
{
    protected function b1()
    {
        echo 'This is in the b class<br />';
    }
}

class c extends a
{
    protected function b1()
    {
        echo 'This is in the c class<br />';
    }
}

$a = new a();
$a->a1();

$b = new b();
$b->a1();

$c = new c();
$c->a1();   
?>

This will result in:

This is in the a class
This is in the b class
This is in the c class

You may also be interested in abstract classes http://us3.php.net/manual/en/language.oop5.abstract.php

Solution 2

use Magic methods of PHP __call or __callStatic

Reference

Share:
18,394
Tural Ali
Author by

Tural Ali

I'm a software architect with 10+ year of experience in various fields.

Updated on June 13, 2022

Comments

  • Tural Ali
    Tural Ali almost 2 years

    I'm new to OO PHP. Got some questions.

    class a {
       protected function a1() {
          ...
       }
    }
    
    class b extends a {
       public function b1() {
          ...
       }
    }
    

    Let's say we have 2 classes like explained above. I'm calling b's method like example below

    class a {
       var $b;
       function __construct()
       {
          $b = new b();
       }
       protected function a1() {
          $b->b1();    
        }
    }
    
    class b extends a {
       public function b1() {
          ...
       }
    }
    

    I know that, it's possible to call parent class'es method from extended class, but I wonder if reverse way is possible? I mean, calling extended classes method from inside parent class (in this case, class b's method from class a) without declaring in __contruct, simply by $this->b();?