This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Interface vs Abstract Class (general OO)
EDIT:
I just read the questions and answers to the questions from "possible duplicate" and I feel really sad that someone considers these two questions even similar... but, oh well...
-------------------------------------------------------------------------
Hello everyone,
I am trying to understand something about Interfaces in OOP paradigm.
I know the difference between abstract class and interface, I also know that interfaces basically allow easy multiple inheritance behaviour and design, but what I don't get is the "principle of promise". I mean, interface should be a promise that a class implementing an interface has all interface methods implemented.
What I don't understand is do we have to check if class implements interface with instanceOf every time we call its methods? Without reading documentation you have no idea some class implements interface. And if you read the code than you can see yourself that there is that method defined and you can call it?!
If I have
case A.
class Ball{
function kick(){...};
}
or
case B.
interface Kickable{
function kick;
}
class Ball implements Kickable{
function kick(){...};
}
the only difference is that in case A I'll get an error when calling a method that it doesn't exist ("in runtime") and in case B I'll get this error when trying to run the code while trying to "compile". Runtime and compile are definitely used wrong here (PHP environment).
I remember in Java there was a Runnable interface which enables threading. Why do we have to implement an interface Runnable and then define run() method in that class? I mean, class could have a Run method without implementing an interface and there are means to check if class has a special method defined. Ok, maybe my Java part of question is a bit confusing :)))
I'm sorry for such a confusing question, but I hope someone went through these problems in understanding and that now he can share his conclusion :)
Thanks,
Luka
You've already named most of the benefits of interfaces in your question, namely:
they allow for multiple (interface) inheritance
You also mention that you know the difference between abstract classes and interfaces. Therein lies another benefit of using interfaces:
Any class can implement an interface, whereas not any class can derive from an abstract class
This is basically a re-hash of the first point above, but it puts it in a perspective that you might not have considered before. Take your Java Runnable example: If Runnable was an abstract class, then any and every class that implements threading would need to inherit from it. That would lead to extremely inflexible code in the end, as you'd not be able to inherit from any other base class. However, since Runnable is an interface, you can have any class implement it (regardless of what base class it may inherit from).
I understand your concern about having to check if a class implements an interface - unfortunately in a weakly typed language you will have to do that, especially since PHP type hinting hasn't totally come into its own yet.
In a strongly typed language, like Java, you generally don't have such concerns, as you will get a compile-time error if you call an interface method on a class that doesn't implement the interface (or doesn't implement the specific method).
No. You haven't to use instanceof. That's for run-time type checking.
If you want to ensure that you are using a class that implements that interface simply put the interface type in your method signature. For example
public interface yourInterface{
public void foo();
}
public class yourClass implements yourInterface{
public void foo(){} //you need to implement this method, otherwise it won't compile
}
public class anotherClass{
public void bar(yourInterface object){} //you can pass any object to "bar" method if the object implements yourInterface. yourClass object will be fine
}
Then some other nice things you can do, depends on your language. For example with java you can force a generic type to implement a given interface, allowing generic programming:
class generiClass<T extends yourInterface>{
public void genericMethod(T object){} //you can use a generic T class, but T needs to implement yourInterface
}
The reason of interfaces are mainly 2:
force a class to implement some methods
Allow multiple inheritance like features in language without multiple inheritance (in language like C++, where you have multiple inheritance, you don't need an interface. Or saying it better, interfaces are quite the same thing of a pure abstract class)
"I also know that interfaces basically allow easy multiple inheritance behaviour and design"
I think you misunderstood that part. Interfaces allow you to ensure that a particular class has a set of properties/methods.
Example:
function foo($obj) {
$obj->bar(); // fails with foo(array());
}
vs:
interface foobar {
function bar();
}
function foo(foobar $obj) { // $obj *must* have a bar() method
$obj->bar();
}
Related
Sorry if this is a duplicate question or a common design principle, I have searched around but was unable to find any answers to this question. I'm probably just searching with the wrong keywords.
I have been looking at a popular library Sabre/Event (https://sabre.io/event/) and in the code there is a simple class/inheritance model that I am trying to understand:
The class EventEmitter implements EventEmitterInterface and uses EventEmitterTrait (see below for code).
There is a comment in EventEmitterTrait above the class which says:
* Using the trait + interface allows you to add EventEmitter capabilities
* without having to change your base-class.
I am trying to understand why this comment says this, and why it allows adding capabilities without changing the base class, and how that is different from just putting the routines into EventEmitter itself.
Couldn't you just extend EventEmitter and add capabilities in the derived class?
Simplified code:
// EventEmitter.php
class EventEmitter implements EventEmitterInterface {
use EventEmitterTrait;
}
// EventEmitterInterface.php
interface EventEmitterInterface {
// ... declares several function prototypes
}
// EventEmitterTrait.php
trait EventEmitterTrait {
// ... implements the routines declared in EventEmitterInterface
}
You're basically asking two questions here.
What are interfaces and why are they useful?
What are traits and why are they useful?
To understand why interfaces are useful you have to know a little about inheritance and OOP in general. If you've ever heard the term spaghetti code before (it's when you tend to write imperative code that's so tangled together you can hardly make sense of it) then you should liken that to the term lasagna code for OOP (that's when you extend a class to so many layers that it becomes difficult to understand which layer is doing what).
1. Interfaces
Interfaces diffuse some of this confusion by allow a class to implement a common set of methods without having to restrict the hierarchy of that class. we do not derive interfaces from a base class. We merely implement them into a given class.
A very clear and obvious example of that in PHP is DateTimeInterface. It provides a common set of methods which both DateTime and DateTimeImmutable will implement. It does not, however, tell those classes what the implementation is. A class is an implementation. An interface is just methods of a class sans implementation. However, since both things implement the same interface it's easy to test any class that implements that interface, since you know they will always have the same methods. So I know that both DateTime and DateTimeImmutable will implement the method format, which will accept a String as input and return a String, regardless of which class is implementing it. I could even write my own implementation of DateTime that implements DateTimeInterface and it is guaranteed to have that method with that same signature.
So imagine I wrote a method that accepts a DateTime object, and the method expects to run the format method on that object. If it doesn't care which class, specifically, is given to it, then that method could simply typehint its prototype as DateTimeInterface instead. Now anyone is free to implement DateTimeInterface in their own class, without having to extend from some base class, and provide my method with an object that's guaranteed to work the same way.
So in relation to your EventEmitter example, you can add the same capabilities of a class (like DateTime) to any class that might not even extend from DateTime, but as long as we know it implements the same interface, we know for sure it has the same methods with the same signatures. This would mean the same thing for EventEmitter.
2. Traits
Traits, unlike interfaces, actually can provide an implementation. They are also a form of horizontal inheritance, unlike the vertical inheritance of extending classes. Because two completely different class that do not derive from the same base class can use the same Trait. This is possible, because in PHP traits are basically just compiler-assisted copy and paste. Imagine, you literally copied the code inside of a trait and just pasted it into each class that uses it right before compile time. You'd get the same result. You're just injecting code into unrelated classes.
This is useful, because sometimes you have a method or set of methods that prove reusable in two distinct classes even though the rest of those classes have nothing else in common.
For example, imagine you are writing a CMS, where there is a Document class and a User class. Neither of these two classes are related in any meaningful way. They do very different things and it makes no sense for one of them to extend the other. However, they both share a particular behavior in common: flag() method that indicates the object has been flagged by a user for purposes of violating the Terms of Service.
trait FlagContent {
public function flag(Int $userId, String $reason): bool {
$this->flagged = true;
$this->byUserId = $userId;
$this->flagReason = $reason;
return $this->updateDatabase();
}
}
Now consider that perhaps your CMS has other content that's subject to being flagged, like a Image class, or a Video class, or even a Comment class. These classes are all typically unrelated. It probably wouldn't make much sense just to have a specific class for flagging content, especially if the properties of the relevant objects have to be passed around to this class to update the database, for example. It also doesn't make sense for them to derive from a base class (they're all completely unrelated to each other). It also doesn't make sense to rewrite this same code in every class, since it would easier to change it in one place instead of many.
So what seems to be most sensible here is to use a Trait.
So again, in relation to your EventEmitter example, they're giving you some traits you can reuse in your implementing class to basically make it easier to reuse the code without having to extend from a base class (horizontal inheritance).
Per Sabre's Event Emitter's docs on "Integration into other objects":
To add Emitter capabilities to any class, you can simply extend it.
If you cannot extend, because the class is already part of an existing
class hierarchy you can use the supplied trait.
So in this case, the idea is if you're using your own objects that already are part of a class hierarchy, you may simply implement the interface + use the trait, instead of extending the Emitter class (which you won't be able to).
The Integration into other objects documentation says:
If you cannot extend, because the class is already part of an existing class hierarchy you can use the supplied trait".
I understand it's a workaround when you already have an OOP design you don't want to alter and you want to add event capabilities. For example:
Model -> AppModel -> Customer
PHP doesn't have multiple inheritance so Customer can extend AppModel or Emitter but not both. If you implement the interface in Customer the code is not reusable elsewhere; if you implement in e.g. AppModel it's available everywhere, which might not be desirable.
With traits, you can write custom event code and cherry-pick where you reuse it.
This is an interesting question and I will try to give my take on it. As you asked,
What is the purpose of using traits to define functions for an interface ?
Traits basically gives you the ability to create some reusable code or functionality which can then be used any where in your code base. Now as it stands, PHP doesn't support multiple inheritance therefore traits and interfaces are there to solve that issue. The question here is why traits though ?? Well imagine a scenario like below,
class User
{
public function hasRatings()
{
// some how we want users to have ratings
}
public function hasBeenFavorited()
{
// other users can follow
}
public function name(){}
public function friends(){}
// and a few other methods
}
Now lets say that we have a post class which has the same logic as user and that can be achieved by having hasRatings() and hasBeenFavorited() methods. Now, one way would be to simply inherit from User Class.
class Post extends User
{
// Now we have access to the mentioned methods but we have inherited
// methods and properties which is not really needed here
}
Therefore, to solve this issue we can use traits.
trait UserActions
{
public function hasRatings()
{
// some how we want users to have ratings
}
public function hasBeenFavorited()
{
// other users can follow
}
}
Having that bit of logic we can now just use it any where in the code where ever it is required.
class User
{
use UserActions;
}
class Post
{
use UserActions;
}
Now lets say we have a report class where we want to generate certain report on the basis of user actions.
class Report
{
protected $user;
public function __construct(User $user)
{
$this->user = $user
}
public function generate()
{
return $this->user->hasRatings();
}
}
Now, what happens if i want to generate report for Post. The only way to achieve that would be to new up another report class i.e. maybe PostReport.. Can you see where I am getting at. Surely there could be another way, where i dont have to repeat myself. Thats where, interfaces or contracts come to place. Keeping that in mind, lets redefine our reports class and make it to accept a contract rather than concrete class which will always ensure that we have access to UserActions.
interface UserActionable
{
public function hasRatings();
public function hasBeenFavorited();
}
class Report
{
protected $actionable;
public function __construct(UserActionable $actionable)
{
$this->actionable = $actionable;
}
public function generate()
{
return $this->actionable->hasRatings();
}
}
//lets make our post and user implement the contract so we can pass them
// to report
class User implements UserActionable
{
uses UserActions;
}
class Post implements UserActionable
{
uses UserActions;
}
// Great now we can switch between user and post during run time to generate
// reports without changing the code base
$userReport = (new Report(new User))->generate();
$postReport = (new Report(new Post))->generate();
So in nutshell, interfaces and traits helps us to achieve design based on SOLID principles, much decoupled code and better composition. Hope that helps
We can use simple inheritance or interface instead of abstraction.
Why do we need to use abstraction in PHP? and How can we hide basic features using abstraction? I am confused using abstraction and interface and inheritance. Where to use which?
Please help to understand me.
I think it's important to, first, clarify terminology, in order to more elaborately answer this question.
inheritance
Inheritance is actually broadly applied to a lot of Object-Oriented programming principles and concepts. It just entails one thing bred from another. So whether you are implementing an interface or extending a class you are still using a form of inheritance. They aren't mutually exclusive concepts.
interface
Try to think of an interface like you would a contract. The contract itself is just a document, usually between two or more parties, that lays out the rules of their relationship. Interfaces, specifically in the context of OOP and PHP, do not provide implementation. They only provide the required public methods that an implementing class MUST implement. Interfaces also cannot be instantiated on their own.
abstract class
The abstract class is similar to an interface in that it cannot be instantiated on its own, but does not necessarily enforce a contract on the extending class. Since it's an actual class, and not just an interface, it also allows for implementation. This implementation can be supplied by the abstract class itself, or left up to the extending class, if the method is declared as abstract in the abstract class. It also allows for the implementation of properties and private/protected methods, because the inheritance here acts like a base class and not just a requirement.
So to answer the question, "why do we have abstract classes in PHP", because it's useful. You may see these as intractable ideas at first, but they actually can work together to provide conjoined utility.
Example
Consider that some times an interface isn't enough to create a useful implementation. The interface can only enforce that a method exists and that its signature is compatible with the implemented interface. There may be cases when you wish to provide default implementations of an interface, for example.
interface Device {
public function input(Stream $in);
public function output(): Stream;
}
abstract class DefaultDevice implements Device {
protected $buffer = "";
public function input(Stream $in) {
$this->buffer .= $in->read(1024);
$this->process();
}
abstract protected function process();
}
So now any class that extends DefaultDevice can either choose to override the implementation of the input method or not. It also has to implement a process method even though the interface does not require it. This means other classes implementing the Device interface can be backwards compatible and this remains an implementation detail.
Further Example
Separating implementation from specification is generally a key attribute of well-written software.
Take a look at the Device interface itself, as a good example. We rely on the input method to accept a Stream type and the output method to return a Stream type. Since Stream, itself, can actually be an interface this means that any type implementing Stream is acceptable. So I could create my own class and implement the Stream interface without ever breaking this code.
class CustomStream implements Stream {
public function read($bytes = 1024) {
/* implementation */
}
public function write($data) {
/* implementation */
}
}
$device->input(new CustomStream); // this will not throw an error
an abstract class is used to provide a set of data members or methods to be made available to classes which inherit from it, even though the base class is not particularly useful (and should never be instantiated on its own) without an inherited implementation.
from here, inheritance takes over.
an interface on the other hand is to provide a set of rules for implementation that require each class that uses the interface to implement the specifications found therein. classes implementing the same interface do not need to inherit from each other, they implement the interface so they can be used in any application requiring that set of functionality.
Just as an exercise lets try to create some classes to handle geometric shapes.
The base class:
class Shape
{
public function draw()
{
}
}
Only the relevant part of the base class is described in the code fragment above. Of course, it should have properties to store its position, line color etc and methods (constructor, at least).
A couple of derived classes:
class Circle extends Shape
{
public function draw()
{
// the code to draw a circle
}
}
class Rectangle extends Shape
{
public function draw()
{
// the code to draw a rectangle
}
}
Can we provide an implementation for method draw() in the base class Shape?
Of course not. Shape is generic, it doesn't mean only "circle" or "rectangle" or "triangle". There is no way to provide a reasonable implementation for Shape::draw() because we don't even know what shape it represents.
Is it ok to provide an empty implementation for Shape::draw()?
Apparently it is. However, on a second thought, it's clear that this is not safe. The objects of a class that extends Shape and doesn't provide its own implementation for method draw() cannot be drawn.
Because the class Shape is not able to provide a decent implementation for method shape, it should signal this thing somehow to the derived classes and force them to provide an implementation.
The way it signals this situation is the abstract keyword. An abstract method tells the readers of the class that the class is not able to provide an implementation because it is too generic and it delegates this responsibility to each class that extends it.
A class that has an abstract method is not completely defined. This is the reason why it is an abstract class and it cannot be instantiated.
Is it a good practice to use in the base class a method which will be defined in a derived one? For instance:
abstract class CApplication {
use TSingleton;
protected final function singletonInstanceInit() {
if (php_sapi_name() == 'cli') {
$this->initCLIApp();
}
else {
$this->initWebApp();
}
}
}
abstract class CWebApplication extends CApplication {
protected function initWebApp() { }
}
abstract class CCLIApplication extends CApplication {
protected function initCLIApp() { }
}
AFAIK this is not a good practice.
Inheritance is needed for the purpose of defining new behaviors and new specialized types of objects. Which means that you could/*should* write a base class now and extend it some time late on.
If the base class knows something about the structure of it's derived classes that's somewhat of a contract, the derived classes need to implement some functions in order to work with that base class in which case "design by contract" springs to mind.
If you need to have a certain function in the derived class maybe it should be declared as an abstract function in the base class or as a method in an interface the class implements.
That way it's not unreasonable for the base class to know about methods implemented in the derived classes.
Also AFAIK other stricter languages would not permit this at compiler level. You would really need to do some refactoring to achieve this in c++ or Java something along the lines of what I said above using abstract functions in the base class or interfaces.
What you are talking about is 2 different schools of thought. I've seen ruby developers doing such stuff because they were using mixins (yes lots of gems do that). On other hand if you go and ask a classic Java programmer he won't recommend you doing that. The type of liberty that you are just showing in your code is what only dynamic typed languages give you (Ya I know some heads would nod saying I used CGLib), they are implementable either in a hackish way for static typed languages or they are not used at all.
Long story cut short, if I were you I would look into scenario and decide if I need such black magic for my given task or not? No rule is bad as long as it doesn't hurt the code quality.
In every example I've seen, extended classes implement the interfaces of their parents. For reference, the following example:
interface MyInterface{
public function foo();
public function bar();
}
abstract class MyAbstract implements MyInterface{
public function foo(){ /* stuff */ }
public function bar(){ /* stuff */ }
}
// what i usually see
class MyClass extends MyAbstract implements MyInterface{}
// what i'm curious about
class MyOtherClass extends MyAbstract{}
Is failure to implement an interface in a child, which is implemented by a parent, considered bad practice or something? Are there any technical drawbacks to omitting the implementation in the child?
I would consider that you are on the right path. There is no need to declare that you are implementing the interface, when extending a class that already implements it. For me it's just another piece of code to maintain if change is needed. So, yes, you are correct!
Is failure to implement an interface
in a child, which is implemented by a
parent, considered bad practice or
something? Are there any technical
drawbacks to omitting the
implementation in the child?
I just can't answer your question better than this guy has:
By their nature, although sometimes
they may look quite similar, abstract
classes and class interfaces serve
very distinct purposes.
The interface of a class is meant as a
tool for the "user" of that class. An
interface is a public presentation for
the class, and it should advertise, to
anyone considering to use it, what
methods and constants are available
and accessible from the outside. So,
as it name suggests, it always sits
between the user and the class
implementing it.
On the other hand, an abstract class
is a tool aimed at helping the
"implementor" of the classes that
extend it. It is an infrastructure
that can impose restrictions and
guidelines about what the concrete
classes should look like. From a class
design perspective, abstract classes
are more architecturally important
than interfaces. In this case, the
implementor sits between the abstract
class and the concrete one, building
the latter on top of the former.
Reference
Thus, it's up to you to decide, based on who is going to use (instantiate) your classes, and who is going to write them. If you are the sole user and writer of your classes, then, maybe, just maybe, you don't need them both. But, if you want to give everyone a stripped down to core bits blueprint for the class writer(s) and class user(s), then you should consider using both abstracting and implementing.
Maybe a little late to the table but I see the above comments do not clarify the main misunderstanding underlying the OP's question.
So the underlying questions are:
Why we use both an Abstract class and an Interface on the same line?
Should both an Abstract method and an Interface declare the same methods at all?
But before some clarifications why to use either of the two above:
Either of them are used by one programmer to define the contract (requirements, obligations, limitations) the other programmers have to obey when they create the concrete classes (and eventually entire software application) based on Abstract classes / Interfaces developed by that programmer.
An Abstract class, in turn, is used to provide the later created concrete class with methods & data structures blueprint via:
data structures declarations (optional),
base implementation of methods (and their signatures, optional)
just methods declarations (similar to an Interface usage, optional).
An Interface is used to provide a concrete class with a methods blueprint via
just methods (and their signatures, optional) declarations.
Here is an example for an Abstract and concrete classes.
abstract class MyAbstractClass {
public function foo() {
// Base implementation of the method here.
}
public function bar() {
// Base implementation of the method here.
}
// Effectively similar to baz() declaration within some interface:
public abstract function baz($value);
}
class MyConcreteClass extends MyAbstractClass {
// foo() and bar() are inherited here from MyAbstractClass.
// baz() must be implemented or declared abstract again.
public function baz($value) {
// implementation.
}
}
Then the questions come:
Why we need an Interface here?
Do we need an Interface to duplicate same method declarations?
The answers:
Due to the fact that PHP allows only single inheritance for each subclass (you cannot write class MyConcreteClass extends MyAbstractClass, MyAnotherClass {}), when we need to expand the concrete class functionality beyond the already used Abstract class we have to declare this additional functionality via one or more Interfaces.
Like this:
class MyConcreteClass
extends MyAbstractClass
implements MyInterface, MyAnotherInterface {
// Methods and data implementations go here.
}
As the result from the answer 1, an Interface better not to duplicate an Abstract class methods' declarations (this is basically useless). An Interface(s) should decalre the methods that may help to enhance the concrete (or another Abstract class, why not) functionality to provide the programmer that will use these with the firm contract for each object built on top of these classes and interfaces.
Finally, answer to the the OP question whether to use an Interface for an Abstract class or for the concrete class is:
use for either or both (or as needed) as long as an Interface enhances a class contract with new methods' declarations.
Is failure to implement an interface in a child, which is implemented by a parent, considered bad practice or something?
The child always implements the interface, it can not go around with this.
I have no clue if that is bad practice or something. I would say it's a language feature.
Are there any technical drawbacks to omitting the implementation in the child?
You can not test the reflection of the abstract class for having the interface for example.
However, abstract class are already an interface, so technically they themselves not really need the interface but you can do so to keep things fluid within the inheritance.
Well, I was confused too, but I think you should use the latter one, You are right, If you implement the interface in the abstract class, then there is no need to write the interface, you can write the method in interface all into abstract as abstract methods, because you will extend the abstract class whatever, and you will have to use the abstract class as a param type when you use the class in other place, that's not a good thing, I think an abstract class should't be used as a param type, while an interface should be.
I am trying to improve my knowledge of OOP in PHP and have been researching abstract classes and interfaces.
What I have learned
They are both classes that cannot be instantiated themselves but can olny be extended (implemented in the case of interfaces)
Abstract classes provide methods and properties for other classes that extend them.
If a class uses an abstract method then the class itself must also be abstract.
If an abstract method is defined within an abstract class, all child classes must define the details of that method. Methods not defined as abstract can be used in the same way as normal methods.
Interfaces define what methods a class that implements it must have. The functionality of the methods are not defined in the interface, the interface just offers a list of methods that must be included in the child class.
An interface does not define any properties.
Classes can implement as many interfaces as they want to but they must define a method for every one of the interfaces they implement
I think that covers the basics. Please feel free to add to that if you think there's anything I have missed.
What I would like to know is if there are any real world examples of implementation of these classes, especially the interface class. Does anyone know of any open source applications that use them that I can browse to better understand them and see where and when they are used effectively? I have come across book examples which use animals which fails to demonstrate the importance of these classes.
The final keyword prevents the class being extended by other classes, example:
class Parent
{
}
class Mother extends Parent
{
}
final class Brother extends Mother /* - This class cannot be extended - */
{
}
class Pet extends Brother
{
}
The Pet class will throw an error stating: Fatal error: Class Pet may not inherit from final class (Brother)
This is also available for methods, so if you do not want to allow the methods to be inherited causing the child class to have the same method acting as an override.
http://php.net/manual/en/language.oop5.final.php
Yo used that you would like some real world examples of what interfaces can be used for, well a database abstraction layer
You have 1 base class which provides the basic methods to iterate your database data, but that would use a sub class for the the database type, such as MySql,MsSql etc, each database type would have its own class, but for the base class to make sure that it has these methods they would all implement the same interface.
Example
interface IDatabaseLayer
{
public function connect();
public function query();
public function sanitize();
//...
}
So the base class knows that MySql and MsSql have the above methods, thus reducing errors and being more organized.
When passing in objects to classes you want to be sure that the Object is of a certain type, PHP5 allows you to define what type of object should be passed into the methods as params.
lets say you have 3 classes
DatabaseCredentials
DatabaseConnection
DatabaseQuery
you can specifically define in the constructuin of DatabaseConnection that you require a DatabaseCredentials class like so:
class DatabaseConnection implements Connectable
{
public function __construct(DatabaseCredentials $ConnectionDetails)
{
$this->Connect($ConnectionDetails->BuildDSN());
}
}
A good way to really get started is by reading here:
http://php.net/manual/en/language.oop5.php
Another feature of PHP5 you may wish to look at is name spaces, this will allow you to keep your code organized, have multiple objects with the same name, makes auto loading more efficiently
Small Example:
namespace Database\MySql
{
class Database{}
}
namespace Database\MsSql
{
class Database{}
}
And you can just use like:
use Database;
$Database = new MySql\Database();
PHP comes with few interfaces predefinded by default: http://www.php.net/manual/en/reserved.interfaces.php
PHP also contains Standard PHP Library (SPL), which defines more:
interfaces http://www.php.net/manual/en/spl.interfaces.php
classes, including abstract ones: http://www.php.net/manual/en/spl.datastructures.php
Zend Framework is also very good example where such concepts are used. http://framework.zend.com/
Not a real world example as such, but one Design Pattern where you usually encounter interfaces and abstract classes is the Command Pattern. See link for example code.
In general, "programming against an interface" is considered good OO practise, because it decouples concrete implementations and let you more easily change them for other implementations, e.g. instead of asking for a specific class
public function fn(ConcreteClass $obj)
{
$obj->doSomething()
}
you just ask that it provides a certain set of methods
public function fn(MyInterface $obj)
{
$obj->doSomething()
}
Interfaces also help teasing apart large inheritance structures. Because PHP supports only Single Inheritance, you'll often see hierarchies like this:
BaseClass -> Logger -> Auth -> User
where each of these contains specific aspects used inside these classes. With an interface, you just do
User implements Loggable, Authenticable
and then include that specific code via Strategy Patterns or Composition/Aggregation, which is ultimately much more maintainable.
For a list of predefined interfaces in PHP see my answer to:
where to find "template" interfaces?.
You may follow the "PHP patterns" series by Giorgio Sironi in dzone or directly in his blog, really interesting if you are interested patterns and OOP.
Also you could take a look to the Best PHP programming book in stackoverflow if you're in need of a good PHP book.
We can say that interface is purely 100% abstract class but abstract is not. Because many time we defines function in abstract class. But in interface class we always declare function.