Saturday 5 June 2021

Php: Abstract classes

Abstract class can have the methods without implementation.

 

Can an abstract class has both abstract and concrete methods (Methods with definition/body)?

Yes

 

Can I create an object to the abstract class?

No

 

How to create an abstract class?

‘abstract’ keyword is used to define an abstract class.

 

Syntax

abstract class ClassName{
    
}

Example

abstract class Logger{
    public function log($msg){
        echo $msg;
    }

    public abstract function debug($msg);
    public abstract function info($msg);
    public abstract function error($msg);
}


In the above example.

a.   log is a concrete method

b.   debug, info and error are abstract methods.

 

How to define abstract method?

Syntax

abstract access_specifier function_name(args){
    
}


Example

abstract public function log();


Another concrete class can extend this abstract class and provide implementation to the abstract methods.

 

abstract_class_demo.php

#!/usr/bin/php

<?php

    abstract class Logger{
        public function log($msg){
            echo $msg;
        }

        public abstract function debug($msg);
        public abstract function info($msg);
        public abstract function error($msg);
    }
    
    class MyLogger extends Logger{
        public function debug($msg){
            $this->log($msg);
        }

        public function info($msg){
            $this->log($msg);
        }

        public function error($msg){
            $this->log($msg);
        }
    }

    $logger = new MyLogger();

    $logger->log("Simple log\n");
    $logger->debug("Debug log\n");
    $logger->info("Info log\n");
    $logger->error("Error log\n");
?>


Output

$ ./abstract_class_demo.php 

Simple log
Debug log
Info log
Error log


Note

a.   If class ‘C’ extending an abstract class ‘A’, then class ‘C’ must provide implementation to all the abstract methods of class ‘A’, else make the class ‘C’ as abstract.





 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment