PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP AdvancedPHP Include and RequirePHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms FinishingPHP OOPPHP OOP IntroductionPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP InterfacesPHP OOP TraitsPHP OOP ConstantsPHP OOP StaticPHP OOP NamespacesPHP OOP Autoloading

PHP OOP Abstract Classes and Methods

When the parent class
  • Knows what to do and
  • Need its child class to do some tasks
it can let its child classes to do the task. This is an abstraction.
PHP OOP Abstract Classes
PHP OOP Abstract Classes

Now you understand abstract classes are something going with inheritance.

Abstract classes have abstract methods in it which they need their children (child classes) to override when inheriting.

Declaring Abstract Classes

The abstract keyword is used to define an abstract class.


<?php
abstract class ParentClass { ... }

Declaring Abstract Methods

When you prepend the abstract keyword to a method's declaration it becomes an abstract method. And, remember, abstract methods do not have a body. Therefore, curly brackets {} are not used.


<?php
abstract class ParentClass {
	abstract public function myMethod1();
	abstract protected function myMethod2($name, $age);
	abstract protected function myMethod3() : int;
}

Abstract method's visibility can either be public or protected, but not private.

The Abstraction Rules

When a child class is inherited from an abstract class, the following rules apply.

  • The child class should override (redeclare) all the abstract methods.
  • The arguments for methods should be the same as the abstract method.

    For instance, in the above example, myMethod2 has two arguments: $name and $age. The method myMethod2 in the child class should have the same arguments.

    
    public function myMethod2($name, $age) {...}	
    
    
  • The child class can have arguments with default values where the abstract class hasn't defined.

    
    public function myMethod2($name, $age, $country = 'USA') {...}	
    
    
  • If the abstract class uses type hinting (type declaration for return values), the child class should use the same.

    For instance, the myMethod3 in the above abstract class hints int. So, the child's method hints the same.

    
    public function myMethod3() : int {...}	
    
    
  • The visibility of the child's method should be the same as the parent's or less restricted.
    Abstract Method's VisibilityChild Method's Visibility
    PublicPublic
    ProtectedProtected or Public
  • Objects cannot be created from abstract classes.

Abstract classes can have non-abstract methods

Non-abstract methods can be defined in an abstract class. Those methods will work as the same as normal methods we had in inheritance.


<?php
abstract class ParentClass {
	abstract public function myMethod1();
	public function myMethod2() {
		echo "Hello World";
	}
}

Remember! This is the main difference between abstract classes and interfaces. Abstract classes can have real methods while interfaces can only have method declarations.

Examples of Abstract Classes in PHP OOP

Let's improve the example we created in the last chapter with the new things we learned in this chapter.

Parent Abstract Class


<?php
abstract class Person {
	public $name;
	public function __construct($name) {
		$this -> name = $name;
	}
	abstract public function greet() : string;
}

Explanation: In the parent class, the __construct method and $name property are declared. So, the child class will automatically have them. But, greet() is a method that should be defined in all the child classes and they should return a string.

Child Classes


<?php
class Programmer extends Person {
	public function greet() : string {
		return "Hello World from " . $this -> name;
	}
}
class Student extends Person {
	public function greet() : string {
		return "Howdy! I'm " . $this -> name;
	}
}
class Teacher extends Person {
	public function greet() :string {
		return "Good morning dear students";
	}
}

Now we can create objects from the child classes.

The Objects


<?php
$programmer = new Programmer('John');
echo $programmer -> greet();

$student = new Student('Doe');
echo $student -> greet();

$teacher = new Teacher('Mary');
echo $teacher -> greet();

Full Code

PHP OOP Abstract Classes Example


<?php
abstract class Person {
	public $name;
	public function __construct($name) {
		$this -> name = $name;
	}
	abstract public function greet() : string;
}
class Programmer extends Person {
	public function greet() : string {
		return "Hello World from " . $this -> name;
	}
}
class Student extends Person {
	public function greet() : string {
		return "Howdy! I'm " . $this -> name;
	}
}
class Teacher extends Person {
	public function greet() :string {
		return "Good morning dear students";
	}
}
$programmer = new Programmer('John');
echo $programmer -> greet();
echo "<br>";

$student = new Student('Doe');
echo $student -> greet();
echo "<br>";

$teacher = new Teacher('Mary');
echo $teacher -> greet();
echo "<br>";

Run Example ››

Conclusion

Abstract classes are important when you strictly need child classes to define a method. In most cases, abstraction is used when the parent class is inherited by multiple child classes which have almost the same behaviors.

What stakoverflow says,
"Use an abstract class when you want to force developers working in your system (yourself included) to implement a set numbers of methods and you want to provide some base methods that will help them develop their child classes."

Also, abstraction is the basis of interfaces which we will discuss in the next chapter.

Facebook Twitter