简体   繁体   中英

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

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

使用PHP __call__callStatic Magic方法

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM