Saturday, March 24, 2007

Class Abstraction

PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract.Methods defined as abstract simply declare the method's signature they cannot define the implementation.
class中包括一个abstract方法以上, 则此class也为abstratct class。Abstract method只是在abstract class 声明一下,并确定此method的visibility,并不具体实现这些方法的功能。这些是在继承类subclass中实现。

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or weaker) visibillity. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public.


<?php
abstract class AbstractClass
{
abstract protected function getValue();
abstract public function addPrefix($prefix);

public function putOut()
{
echo "<br>", $this->getValue(), "<br>";
}
}

class ConcreteClass extends AbstractClass
{
public function getValue()
{
echo "<br>", "Concrete Class.", "<br>";
}
// Fatal error: Class ConcreteClass contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (AbstractClass::addPrefix)
// Fatal error: Access level to ConcreteClass::addPrefix() must be public (as in class AbstractClass)
public function addPrefix($prefix)
{
echo "<br>", "{$prefix}Concrete Class.", "<br>";
}
}

$c = new ConcreteClass();
$c->putOut();
$c->addPrefix("yu_");
?>

No comments :