简体   繁体   中英

PHP Class extending an Abstract cannot run a function that has the same name as the Abstract Class

This code fails. But I don't understand why. If I change the function lol to function anything else, it works. If I change the class of the Abstract it also works. See this execution: http://codepad.viper-7.com/Z9V67x

<?php

abstract class Lol{

    abstract public function lol($external = false);

}

class Crazy extends Lol{

    public function lol($external = false){
            echo 'lol';
    }

}

$new = new Crazy;

$new->lol('fdgdfg');

The error that comes back is:

Fatal error: Cannot call abstract method Lol::lol() in /code/Z9V67x on line 17 PHP Fatal error: Cannot call abstract method Lol::lol() in /code/Z9V67x on line 17

Doing some research on same name functions and classes, in PHP4 the same name meant a constructor. According to this https://stackoverflow.com/a/6872939/582917 answer, namespaced classes no longer treated functions with the same name as the constructor. BUt non namespaced classes do. Still why can't the constructors be replaced in the child instance?

check code below:

abstract class Lol{
    public function __construct() { // only one constructor is really needed
    }
    abstract public function lol($external = false);
}

class Crazy extends Lol{
    public function __construct() { // only one constructor is really needed
    }
    public function Crazy() { // only one constructor is really needed
    }
    public function lol($external = false) {
        echo 'lol';
    }
}

$new = new Crazy();
$new->lol('fdgdfg');

it works ok, why?

PHP is not very good with OOP, even latest version, it has PHP4 legacy, so lets try to understand what your code do:

  1. it defined abstract function, which is understand by php as constructor and as abstract method
  2. in sub class you're defining only method, but constructor is still abstract

this is why you're getting error during new - php really cannot find constructor

now check code above - it has 3 constructors, you can have any 1 and this code will work

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