Ouroboros
Ouroboros

Reputation: 1524

Extends in PHP not working when method in Base class tries to invoke a method which is implemented only in extended class

I'm trying to use extends design pattern in PHP. The idea is to extend some method from a base class, which calls a method which will only be implemented by the extended class, as follows:

class BaseClass {

    function process() {
       $tableName = self::getTable();
       // Do some processing using $tableName returned
    }

}

class ExtendedClassA extends BaseClass {

    function getTable() {
        return "Table_A";
    }
}

The problem is when I try to create an instance of ExtendedClassA, and invoke process function, the above code generates an error, and it would say :

PHP Fatal error: Call to undefined method BaseClass::getTableName()

Any clues what I'm doing wrong?

Upvotes: 2

Views: 211

Answers (2)

Fabian Schmengler
Fabian Schmengler

Reputation: 24551

To call self::getTable(), getTable must be a static method of BaseClass, because self is always bound to the class where the current method is defined.

If you want to call a static method of the currently called class, use static::getTable() instead. This is called late static binding, i.e. static is bound to the class at runtime.

Also, change function getTable() to static function getTable(), otherwise you will get an error (depending on your PHP version and error strictness)

Upvotes: 0

Mantas
Mantas

Reputation: 4296

Implement getTable in BaseClass. Make it empty or abstract. Also use $this instead of self.

Probably BaseClass should be an abstract class as you can't use it directly:

    abstract class BaseClass {

        function process() {
           $tableName = $this->getTable();
           // Do some processing using $tableName returned
        }

        abstract function getTable();

    }

class ExtendedClassA extends BaseClass {

    function getTable() {
        return "Table_A";
    }
}

Upvotes: 1

Related Questions