PHP Code:
interface PageInterface
{
public function render();
}
Here are two classes that implement PageInterface. Notice how both classes contain the public render function (without arguments), if you fail to declare this function PHP will throw a fatal error.
PHP Code:
class Login implements PageInterface
{
public function render()
{
return 'Render Login Page';
}
}
class Register implements PageInterface
{
public function render()
{
return 'Render Register Page';
}
}
As we've defined both Register and Login as types of PageInterface we can treat them as the same (as types of Page, anyway). Let's say, for some reason you wanted to create collections of pages and render them together -- you probably wouldn't, but it provides a good base for this example -- then you can use the PageInterface to ensure that this collection of Pages all follow the same interface. Since they all follow this interface, they will all implement the render() function.
PHP Code:
class PageCollection
{
private $pPage = array();
public function add(PageInterface $pPage)
{
$this->m_aPageCollection[] = $pPage;
}
public function renderPages()
{
foreach ($this->m_aPageCollection as $pPage)
{
echo $pPage->render();
}
}
}
Inside the renderPages() method, when we're looping through the collection of pages, we can happily call $pPage
This is a good example of polymorphism: When we call render() we know that it will render a page, but we don't know what sort of page we're rendering. Thus, the render() function has many forms (polymorhpism, means many-forms), because it can render a Login page, Register page, or any other "form" of page.
Here's an example of how the class can be used to create and render a collection of pages.:
PHP Code:
$pPageCollection = new PageCollection();
$pPageCollection->add(new Login());
$pPageCollection->add(new Register());
$pPageCollection->renderPages();
PHP Code:
$pPageCollection = new PageCollection();
$pPageCollection->add(new Login());
$pPageCollection->add(new Register());
// Try to add a DateTime object, this will cause a fatal error
$pPageCollection->add(new DateTime());
$pPageCollection->renderPages();
PHP Code:
interface AdminPageInterface
{
public function auth();
}
class AdminNews implements PageInterface, AdminPageInterface
{
public function auth()
{
echo "Auth Code";
}
public function render()
{
echo "Render Code";
}
}


Join the friendly bunch on IRC...