Thread: Need an example

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    12
    Rep Power
    0

    Need an example


    can anyone please explain me the use of abstract class with an example..i tried a couple of tutorials but not getting the idea of it..why would we use abstract class in php..

    thanks in advance
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,901
    Rep Power
    1045
    Hi,

    do you know interfaces and what they're for? An interface is a "contract". It only specifies which methods a class should have without actually implementing them.

    An abstract class is something between an interface and a regular class: It implements some methods, but other methods are left abstract and must be implemented by the subclasses.

    As an example: Let's say you wanna access different resources (files, severs, whatever) in an object-oriented way. A resource has different actions like "read_all", "read_bytes", "write", maybe "delete" etc. However, you cannot implement all methods in the generic Resource class, because how exactly something is read or written depends on the concrete resource. On the other hand, you can implement some of the higher-level methods like "read_all", because those are only combinations of the other methods.

    The solution to this is to use an abstract class, which allows you to implement some methods while leaving the others abstract.

    PHP Code:
    <?php

    abstract class Resource {

        
    // the subclasses should implement those:
        
    abstract function read_bytes($num_bytes);
        abstract function 
    reached_end();
        
        
    // this is what we can already implement:
        
        
    public function read_all() {
            
    $content '';
            while (!
    $this->reached_end())
                
    $content .= $this->read_bytes(32);
            return 
    $content;    
        }

    }



    class 
    File extends Resource {

        private 
    $source;

        public function 
    __construct($path) {
            
    $this->source fopen($path'r+');
        }
        
        public function 
    __destruct() {
            
    fclose($this->source);
        }
        
        
    // now we have to implement the abstract methods; the concrete methods from Resource are simply inherited
        
        
    public function read_bytes($num_bytes) {
            return 
    fread($this->source$num_bytes);
        }

        public function 
    reached_end() {
            return 
    feof($this->source);
        }

    }



    // use the File class
    $file = new File('path/to/some/file');
    echo 
    $file->read_all();

IMN logo majestic logo threadwatch logo seochat tools logo