Abstract classes and methods in PHP. Code examples open

Abstract classes and methods in PHP. Code examples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: PHP 7

When creating a regular class in PHP, you can make it abstract by adding the abstract modifier before the class name. Its peculiarity is that we cannot directly create abstract class objects. Abstract classes serve as a kind of framework for building other classes based on them.

	
abstract class Profile {};

Abstract classes, like ordinary classes, can define variables and constants, methods and constructors.

Abstract methods

Abstract classes can contain abstract methods. These are methods that have no implementation. Implementation for them is provided by derived classes.

abstract class Profile
{
    abstract function create($profiledata);  
}
! Abstract methods can only be placed in abstract classes
!If a non-abstract class inherits from an abstract class, then it must implement all of its abstract methods.

Inheritance

Inheritance of abstract classes is no different from inheritance of ordinary classes. To inheritance use the keyword extends.

abstract class Profile
{
    protected $name;

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

    abstract function create($profiledata);

}
 
class ProfileCreator extends Profile 
{
    function create($name)
{
echo "Profile created";
}

$outlook = new ProfileCreator("Alexander");

Abstract classes are very similar to interfaces, however, abstract classes, like ordinary classes, can have variables, non-abstract methods, constructors, but interfaces cannot.

Interfaces in PHP. Code examples open
Interfaces in PHP. Code examples
May 17, 2022
Roman-tk

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation