Memory App
 



Programming > Php > Oop > Interfaces, abstract   ZCE 5.3  |  Patterns  |  Modern Php

Abstract

Abstract and Interfaces are design to create a series of constrains. Abstract class defines a basic skeleton, cannot be used directly.

<?php    
    abstract class A {
        abstract function a();
        public function b() {}
    }

    class B extends A {}

    // Fatal error: Class B contains 1 abstract method
    // and must be declared abstract or implement the remaining methods (A::a)

<?php
    abstract class myAdapter {
        
        private $id;
        abstract function insert();
        abstract function update();

        public function save() {
            if (!is_null($this->id)) {
                $this->update();
            } else {
                $this->insert();
            }
        }
    }

    class PDO_myAdapter extends myAdapter{
        
        public function __construct($dsn) {
            // ...
        }
        public function insertWrongName() {
            // ...
        }
        public function update() {
            // ...
        }

        // Fatal error: Class PDO_myAdapter contains 1 abstract method
        // and must therefore be declared abstract or implement the remaining methods 
        // (myAdapter::insert)
    }
(1/2)

Interface

Interfaces are used to specify an API that a class must implement; contain no body.

<?php
    interface myAdapter {
        public function insert();
        public function update();
        public function save();
        public function foo($name=null);
    }

    class PDO_Adapter implements myAdapter {
        
        public function insert() {
            // ...
        }
        public function update() {
            // ...
        }
        public function save() {
            // ...
        }
        public function foo($name) { // must be $name=null
            // ...
        }
        // Fatal error: Declaration of PDO_Adapter::foo() 
        // must be compatible with that of myAdapter::foo() 
    }
A class can only extend one parent class, but it can implement multiple interfaces.

<?php
    class PDO_Adapter extends PDO implements myAdapter, SeekableIterator {
        ...
    }
You can check if an object is an instance of a particular class.
    
<?php
    class foo {}

    $foo = new foo;

    if ($foo instanceof foo) { // true
        echo "Object $foo is an instance of MyClass";
    }


Questions
0/0 (80)  
Not Logged