Friday, May 18

Object-Oriented Programming Concepts in PHP – Interface

Interface

Interfaces are defined in the same way as a class, but with the interface keyword replacing the class keyword and without any of the methods having their contents defined.
All methods declared in an interface must be public; this is the nature of an interface.
Interfaces allow you to create code which specifies which all methods a class must implement.
Note that it is possible to declare a constructor in an interface.

Implements

  • To implement an interface, the implements operator is used.
  • All methods in the interface must be implemented within a class; failure to do so will result in a fatal error.
  • Classes may implement more than one interface if desired by separating each interface with a comma.
  • Interfaces can be extended like classes using the extends operator.
  • The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.

Example:

<?php
// Declare the interface 'myImplement'
interface myImplement
{
public function setVariable($name, $val);
public function getVariable($tempdata);
}
// Implement the interface
class temp implements myImplement
{
private $vars = array();
 // Implementing the SetVatiable  Method
public function setVariable($name, $val)
{
       $this->vars[$name] = $name;
       $this->vars[$val] = $val;
}
 // implementing the GetVariable Method
public function getVariable($tempdata)
   {
       foreach($this->vars as $name => $value) {
        $tempdata = str_replace('{' . $name . '}', $value, $tempdata);
    }
//return the result
    return $tempdata;
}
}
// Instance creation ( object)
$objTemp = new temp();
// set the values to setvariable method
$rest=$objTemp -> setVariable('bala','Welcome');
$rest=$objTemp -> setVariable('balaa','Welcome1');
$rest=$objTemp -> setVariable('bala1','Welcome2');
$rest=$objTemp -> setVariable('bala2','Welcome3');
// get the value from getvariable method
$objTemp -> getVariable($rest);
echo "<pre>";
print_r($objTemp);
?>


OUTPUT:

temp Object
(
   [vars:temp:private] => Array
       (
           [bala] => bala
           [Welcome] => Welcome
           [balaa] => balaa
           [Welcome1] => Welcome1
           [bala1] => bala1
           [Welcome2] => Welcome2
           [bala2] => bala2
           [Welcome3] => Welcome3
       )

)

No comments:

Post a Comment

Backup files to google drive using PHP coding

 Dear All, To backup files to Google Drive using PHP coding, you can use the Google Drive API and the Google Client Library for PHP. Here...