Tural Ali
Tural Ali

Reputation: 23250

Calling extended class function from parent class

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();?

Upvotes: 7

Views: 22052

Answers (2)

Nate
Nate

Reputation: 1303

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 https://www.php.net/manual/en/language.oop5.abstract.php

Upvotes: 10

xkeshav
xkeshav

Reputation: 54022

use Magic methods of PHP __call or __callStatic

Reference

Upvotes: 4

Related Questions