Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding methods in PHP?

In other OO languages like Java we can override a function, possible using keywords/annotations like implements, @override etc.

Is there a way to do so in PHP? I mean, for example:

class myClass {
    public static function reImplmentThis() { //this method should be overriden by user
    }
}

I want user to implement their own myClass::reImplementThis() method.

How can I do that in PHP? If it is possible, can I make it optional?

I mean, if the user is not implementing the method, can I specify a default method or can I identify that the method is not defined (can I do this using method_exists)?

like image 512
Jinu Joseph Daniel Avatar asked Nov 04 '22 08:11

Jinu Joseph Daniel


1 Answers

<?php
abstract class Test
{
    abstract protected function test();

    protected function anotherTest() {

    }
}

class TestTest extends Test
{
    protected function test() {

    }
}

$test = new TestTest();
?>

This way the class TestTest must override the function test.

like image 98
Dillen Meijboom Avatar answered Nov 15 '22 01:11

Dillen Meijboom