Home > Backend Development > PHP Tutorial > How to Access Child Class Methods from a Parent Class in PHP?

How to Access Child Class Methods from a Parent Class in PHP?

Linda Hamilton
Release: 2024-10-19 08:30:02
Original
233 people have browsed it

How to Access Child Class Methods from a Parent Class in PHP?

PHP: Accessing Child Class Methods from a Parent Class

Often, when working with inheritance in PHP, developers encounter the need to access functions from a child class within the parent class. This can be achieved through a powerful mechanism: abstract classes.

Consider the example code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<code class="php">class whale

{

  function __construct()

  {

    // some code here

  }

 

  function myfunc()

  {

    // how do i call the "test" function of fish class here??

  }

}

 

class fish extends whale

{

  function __construct()

  {

    parent::__construct();

  }

 

  function test()

  {

    echo "So you managed to call me !!";

  }

}</code>

Copy after login

To access the "test" function from within the "whale" class, we can declare the parent class as abstract and define an abstract method corresponding to the child class function.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

<code class="php">abstract class whale

{

  function __construct()

  {

    // some code here

  }

 

  function myfunc()

  {

    $this->test();

  }

 

  abstract function test();

}

 

class fish extends whale

{

  function __construct()

  {

    parent::__construct();

  }

 

  function test()

  {

    echo "So you managed to call me !!";

  }

}</code>

Copy after login

Now, any class inheriting from "whale" will be forced to implement the "test" method. This ensures that all child classes have access to the functionality provided by the abstract method.

By implementing this approach, you can access child class functions from within the parent class, enabling a flexible and extensible inheritance model in PHP.

The above is the detailed content of How to Access Child Class Methods from a Parent Class in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template