Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract class method declaration

Tags:

oop

php

I just wrote code like this:

<?php
class test
{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);

// Common method
public function printOut() {
    print $this->getValue() . "\n";
}
}
class testabs extends test{

public function getValue()
{

}
public function prefixValue($f)
{

}
}
$obj = new testabs();
?>

When I run this code, I received the error below:

Fatal error: Class test contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (test::getValue, test::prefixValue) in C:\wamp64\www\study\abstract.php on line 12

I understand the first part of this error. I changed the class test to abstract and the error is gone, but the or part i can't understand.

like image 400
Anish Chandran Avatar asked Oct 02 '16 05:10

Anish Chandran


1 Answers

If you are going to add abstract methods, then you will need to make the class abstract as well. That way, the class cannot be instantiated- only non-abstract sub-classes can be.

The method visibility (refer to the second sub-section Method Visiblilty) is not the same in the sub-class. Depending on whether you want the methods to be called by code outside of sub-classes, you can declare the (abstract) methods in class test with visibility public, or else declare the sub-class methods also with visibility protected.

And note the second paragraph from the Class Abstraction page, which explains this:

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private

<?php
abstract class test{
    // Force Extending class to define this method
    abstract protected function getValue();
    abstract protected function prefixValue($prefix);

    // Common method
    public function printOut() {
        print $this->getValue() . "\n";
    }
}
class testabs extends test{

    protected function getValue()
    {

    }
    /**
    *   this method can be called from other methods with this class 
    *   or sub-classes, but not called directly by code outside of this       class
    **/
    protected function prefixValue($f)
    {

    }
}
$obj = new testabs();
// this method cannot be called here because its visibility is protected
$obj->prefixValues();// Fatal Error
?>
like image 113
Sᴀᴍ Onᴇᴌᴀ Avatar answered Sep 21 '22 05:09

Sᴀᴍ Onᴇᴌᴀ