Thread: Need an example

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

    Join Date
    Jul 2013
    Rep Power

    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
    Rep Power

    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:

    abstract class Resource {

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


    File extends Resource {


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

        public function 
    reached_end() {


    // use the File class
    $file = new File('path/to/some/file');
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".

IMN logo majestic logo threadwatch logo seochat tools logo