What Is an Abstract Class in PHP

What is an abstract class in PHP?

An abstract class is a class that contains at least one abstract method, which is a method without any actual code in it, just the name and the parameters, and that has been marked as "abstract".

The purpose of this is to provide a kind of template to inherit from and to force the inheriting class to implement the abstract methods.

An abstract class thus is something between a regular class and a pure interface. Also interfaces are a special case of abstract classes where ALL methods are abstract.

See this section of the PHP manual for further reference.

PHP: what is the use case of abstract class

However, when I tried the same example above with a little bit of tweak, removing all the abstractions (given below) I see the exact same output as the previous example.

PHP is dynamically typed so the parent class can access methods that 'may or may not exist'1; the same polymorphism still holds (for non-private methods). In a languages like Java or C#, the code would have failed to compile. (Interface/contract checking is a separate issue2.)

Thus both examples are technically valid in PHP and will produce the same output, without error or warning.

Is there other cases where I must or it is highly recommended to use [abstract methods]?

It is 'more correct' when applying nominative types / class declarations to annotate the method as abstract as this:

  • Establishes a guarantee that an implementation is provided by concrete subclasses2

  • Provides additional information for type-checking tools; and is a safeguard if stricter type checking is applied in the future

  • Declares a method signature and documentation stub; and appears in type reflection

The linked example/documentation already explain the semantic goal of abstract methods. (However it is fraught with some .. questionable wording; eg. private methods cannot be abstract.)


1 This is also known as duck typing and is allowed in many other dynamic languages - including Ruby, Python, and JavaScript - which support OO and and the same concept of abstract methods, albeit less formally, as expressed through subtype polymorphism.

2 Interface/contract checking (which is only done for type definitions) ensures that the implementing class, or subclass for abstract classes, must conform to the specified types. In the case of abstract methods this means that subclasses must provide method implementations or be abstract themselves.

Abstract Classes in OOP PHP

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

What are the advantage if i use abstract class in php?

What are the advantage if i use abstract class in php? i cant find anything good on that. I think i can easily do all work with out using the abstract class?

You could, naturally. However, if there are many objects that are of pretty much the same type, it might help to extract common functionality out into a "base" class, which means you don't have to duplicate that logic.

There are actually two reasons though. The first reason, for me, would be that all descendants of your abstract class have the same type, and both adhere to the exact same interface. That means that a PDF document for example will have the same interface as a docx document, and the client code doesn't have to care which object it's handling. Short example (in PHP).

<?php
abstract class Document {
protected $author;

public function __construct( $author ) {
$this->author = $author;
}

abstract public function render( );

public function author( ) {
return $this->author;
}
}

class PdfDocument extends Document {
public function render( ) {
// do something PDF specific here.
}
}

class DocxDocument extends Document {
public function render( ) {
// do something DOCX specific here.
}
}

class DocumentHandler {
public function handle( Document $document ) {
$this->log( 'Author has been read ' . $document->author( ) );
return $document->render( );
}
}

First of all; mind the fact that the DocumentHandler class has no knowledge of which type of Document it's actually handling. It doesn't even care. It's ignorant. However, it does know which methods can be called upon, because the interface between the two types of Documents are the same. This is called polymorphism, and could just as easily be achieved with the implementation of a Document interface.

The second part is; if each and every document has an author, and that author is always requested, you could copy the method over to the PdfDocument as well as the DocxDocument, but you'd be duplicating yourself. For instance, if you decide that you want the author to written with capitals, and you'd change return $this->author to ucwords( $this->author ), you'd have to do it as many times as you've copied that method. Using an abstract class, you can define behaviour, while marking the class itself as incomplete. This comes in very handy.

Hope that helps.

What exactly is an abstract class in php?

Abstract Class – In PHP, these two features of object-oriented programming are used very frequently. Abstract classes that can't be instantiated rather they can be inherited. The class that inherits an abstract class can also be another abstract class. In PHP we can create an abstract class by using the keyword – 'abstract'.

Listing 5 – Sample code for Abstract Class

abstract class testParentAbstract {
public function myWrittenFunction() {
// body of your funciton
}
}

class testChildAbstract extends testParentAbstract {
public function myWrittenFunctioninChild() {
// body of your function
}
}

In the above example, we can create an instance of the child class – testChildAbstract, but we can't create the instance of the parent class – testParentAbstract. As we see that the child class is extending the parent class, we can use the property of the parent class in the child class. We can also implement an abstract method in our child class as per our need.

Source . http://www.phpbuilder.com/articles/application-architecture/object-oriented/advanced-object-oriented-programming-in-php.html

PHP - if all methods in abstract class are abstract then what is the difference between interface and abstract class

An Abstract Class allows for "partial implementation" (see the template method pattern), but in this case, if all methods are abstract, you don't see that benefit. One other thing you can do is include fields, you're not just limited to methods.

Remember, there's a conceptual difference between an "abstract method" and the contract defined by an interface. An abstract method has to be overridden by a subclass which is done through inheritence implementation. Any polymorphic calls (downcasting) will require one superclass per class or it would hit the diamond inheritance problem. This kind of inheritence based tree structure is typical of OO design.

As a contrast, an interface provides a signature of a contract to fulfil. You can fulfil many interface's needs as long as you retain the signature as there is no question of going back up the class hierarchy to find other implementations. Interfaces don't really rely on polymorphism to do this, it's based on a contract.

The other thing of note is you may have "protected" abstract methods, it makes no sense to do such a thing in an interface (in fact it's illegal to do so).

Difference in abstract class implementation in c# and php

C# has static typing. That's why you can't access a field or property that is declared in a subclass. You have to declare Hair as an abstract property in Person and implement it in the subclass:

    abstract class Person
{
public abstract void SetHairColor(string hair);

public abstract string Hair { get; }

public string getHairColor()
{
return this.Hair; // now it is accessible
}

}

class Male : Person
{
private string _Hair;
public override string Hair { get { return _Hair; } }

public override void SetHairColor(string hair)
{
this._Hair = hair;
}
}

You can also implement SetHairColor as setter of the property Hair:

    abstract class Person
{
public abstract string Hair { get; set; }

public string getHairColor()
{
return this.Hair; // now it is accessible
}

}

class Male : Person
{
private string _Hair;
public override string Hair
{
get { return _Hair; }
set { _Hair = value }
}
}


Related Topics



Leave a reply



Submit