Is it possible to implement an abstract class in PHP without the need for inheritance like in Java?

2

It is possible to do in PHP "in the same way" the instance of class CachorroAbstract in method main below:

public abstract class CachorroAbstract {
    public abstract void latir();
}
public class Main{
    public static void main(String[] args) {
        CachorroAbstract cachorro = new CachorroAbstract() { //AQUI
            @Override
            public void latir() {
                 System.out.println("AU! AU!");
            }
        };
        cachorro.latir();
    }
}
    
asked by anonymous 04.07.2016 / 22:47

1 answer

3

Without inheritance it is impossible. But you do not need to use a class to instantiate later if you're using PHP 7. In previous versions it does not. You might even have other techniques without using object orientation, but that's not what you want.

In PHP 7 it is possible with the new class extends syntax. This is called anonymous class in both languages. Something like this:

$cachorro = new class extends CachorroAbstract { ... };
    
05.07.2016 / 00:30