0

Why would you want to declare an abstract method in the example below,

<?php

    abstract class ClassName
    {
        abstract public function methodName();
    }
?>

when

<?php

    class ClassName
    {
        public function methodName()
        {
           // Body of method
        }
    }
?>

would provided the same results when manipulated by an inheriting child class.

blakroku
  • 531
  • 5
  • 12
  • 4
    https://en.wikipedia.org/wiki/Abstract_type#Use_of_abstract_types "Abstract types are useful in that they can be used to define and enforce a protocol; a set of operations that all objects implementing the protocol must support." – ceejayoz Jun 07 '16 at 23:37
  • 1
    Well no it doesn't provide the same results. Any child class wouldn't be forced to override `methodName`. To answer **why**, that's really up to you to decide. It's like asking why ENUMs exist, it helps you write maintainable code. – Dave Chen Jun 07 '16 at 23:38
  • 1
    so, continuing from @ceejayoz's citation - it helps you to keep your code more clean and strict. – strangeqargo Jun 07 '16 at 23:39
  • 1
    To make a concrete example: imagine `abstract class CacheStore`, intended to be used for a Redis store, a MySQL store, a file store, and an AWS S3 store. The Redis store would never want to inherit the MySQL store's implementation - they're totally different. By having an abstract class, you can say "any cache store will have a get/put/expire/delete" etc. function with the same name and signature, but the underlying implementation can be entirely different. – ceejayoz Jun 07 '16 at 23:41
  • @ceejayoz, this begs the question of why PHP has abstract classes when it *also* has an `interface` keyword. – alexis Jun 07 '16 at 23:43
  • 1
    @alexis http://stackoverflow.com/questions/1814821/interface-or-an-abstract-class-which-one-to-use – ceejayoz Jun 07 '16 at 23:45
  • @alexis To extend the `CacheStore` example, an abstract store class could provide a `getMultiple` method already implemented that calls the store's `$this->get()` a few times. The implementation for *that* method would sensibly be the same across all store types, so it makes sense to be in the abstract class itself instead of making each store type re-implement the same logic. – ceejayoz Jun 07 '16 at 23:46
  • @ceejayoz, I was just pointing out that your comment conflates interfaces and abstract classes (but it's just a comment, of course). The question you link to is a good resource. – alexis Jun 08 '16 at 00:09

1 Answers1

3

Guidance to the programmer. The two code examples you give are only equivalent if used correctly. A class containing stub methods can be intantiated and used, but it silently fails to do what needs to be done. An abstract class will raise an error unless a child class is derived and all the abstract methods overridden.

alexis
  • 48,685
  • 16
  • 101
  • 161