Click to See Complete Forum and Search --> : What are object interfaces?


Nate
09-08-2004, 03:37 PM
http://us2.php.net/manual/en/language.oop5.interfaces.php

I'm trying to understand what these are used for... Could someone explain that first sentence on that page to me in laymen's terms?

Thanks!

Weedpacket
09-08-2004, 06:02 PM
They're largely a self-documenting device for the benefit of programmers. An object interface is a list of functions that any class implemeting it must supply code for. If you're writing a class that implements the Foobar interface, and the Foobar interface lists a function called "super_foonly()" but you accidentally forget to write that function, PHP will throw an error.

The other side of the coin is that if you write an object interface, you can be assured that any class written implementing that interface will have the functions listed and you can therefore call them, assured that they will be there.

Nate
09-08-2004, 06:13 PM
Thanks! That makes perfect sense.

Weedpacket
09-09-2004, 04:54 AM
One other use of interfaces I forgot to mention is that your program can check to see if an object implements a particular interface in the same way that it can ask that object what class it is (or is descended from).

If an object implements the FooBar interface, then your code can check that it does by using ($object instanceof FooBar). The result will be true or false.

The same check can be made at runtime when the function is called:

function your_function(FooBar $object)
{
....
}

and if $object doesn't implement the FooBar interface, then when your_function() is called, PHP will whinge.