Rakesh K
Rakesh K

Reputation: 1320

Abstract Classes in OOP PHP

I am having very strange behavior in my abstract class.

here is my code :

<?php

class Hello {

    public abstract function sayHello();

}

class Hey extends Hello {

public function sayHello(){
    return "Hello";
}

}


$greeting = new Hey;

echo $greeting->sayHello();

So, I am expecting result: Hello

But I cant understand why I am getting following error :

Fatal error: Class Hello contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Hello::sayHello) in /Applications/MAMP/htdocs/oop/abstract.php on line 7

What am I missing?

Upvotes: 2

Views: 727

Answers (1)

Syscall
Syscall

Reputation: 19780

You missing to declare class as abstract :

// here, class should be declared as abstract
abstract class Hello {

    public abstract function sayHello();

}

class Hey extends Hello {

    public function sayHello(){
        return "Hello";
    }

}


$greeting = new Hey;

echo $greeting->sayHello();

Outputs :

hello

Upvotes: 7

Related Questions