简体   繁体   中英

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?

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";
    }
}

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 , ie 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)

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