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

Asked

Viewed 119 times

2

It is possible to perform the class instance in PHP "in the same way" CachorroAbstract in the method main down 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();
    }
}
  • Use interface :)

  • Hello diegofm, thank you for the reply. In fact my php class has some implemented methods, I did this in java to be very brief, and these implemented methods make use of the returns of the methods.

1 answer

3


No inheritance is impossible. But you don’t need to use a class to instantiate later, if you’re using PHP 7. In previous versions you can’t. I would even have another kind of technique without using object orientation, but it’s not what you want.

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

$cachorro = new class extends CachorroAbstract { ... };

I put in the Github for future reference.

  • Hello bigown, Thanks for the reply! I believe I won’t be able to use PHP 7, but still, thank you very much for the info!

  • Yeah, this is a complication :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.