Page 1 of 1

about interface

Posted: Sat Feb 20, 2010 6:30 am
by belal_nabeh
Hi
i have a question in OOP
what is the difference between these code
and what is the benefit when i'm using interface

Code: Select all

 
interface IUser
{
    function getName();
}
class User implements IUser
{
    public static function Load( $id )
    {
        return new User( $id );
        return;
    }
    
    public function __constructs( $id )
    {
        return;
    }
    
    public function getName()
    {
        echo "Belal";
        return;    
    }
}
 
$ob = User::Load( 1 );
$ob->getName();
 
and

Code: Select all

 
class User
{
    public static function Load( $id )
    {
        return new User( $id );
        return;
    }
    
    public function __constructs( $id )
    {
        return;
    }
    
    public function getName()
    {
        echo "Belal";
        return;    
    }
}
 
$ob = User::Load( 1 );
$ob->getName();
 
each one work exactly same the other.

Thanks..

Re: about interface

Posted: Sat Feb 20, 2010 7:15 am
by requinix
Interfaces are for functionality, classes are for objects.
If you want objects to be able to act a certain way you use interfaces. If one object is a more specific version of another object, use classes.

Typically a "User" is a class, not an interface.

Re: about interface

Posted: Sat Feb 20, 2010 7:47 am
by belal_nabeh
thank you for your help
but would you please give me more explanation about it
and how i can use it

Re: about interface

Posted: Sat Feb 20, 2010 8:03 am
by VladSun
I'd say you should use class (object) when its name is a noun, and you should use interface when you may use an "*-able" to describe all of the features needed.
E.g.
User => class
Printable => interface

A common situation is to have a collection-like object (e.g. a linked list) which implements Traversable in order to be used in a foreach loop.

http://www.php.net/~helly/php/ext/spl/i ... sable.html

Re: about interface

Posted: Sat Feb 20, 2010 8:03 am
by requinix
I'm not going to write a treatise on OOP because there are too many other people who have:
http://www.google.com/search?q=interfaces+vs+classes
The articles involving Java will be some of the best: Java is very, very object-oriented.

Re: about interface

Posted: Sat Feb 20, 2010 8:53 am
by belal_nabeh
thanks alot for all