search for in the  
<Object ConstantsObject Interfaces>
Last updated: Thu, 19 May 2005

Object 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.

The class that implements the abstract method must define with the same visibillity or weaker. If the abstract method is defined as protected, the function implementation must be defined as either protected or public.

Example 19-16. Abstract class example

<?php
abstract class AbstractClass
{
  
// Force Extending class to define this method
  
abstract protected function getValue();

  
// Common method
  
public function printOut() {
       print
$this->getValue();
   }
}

class
ConcreteClass1 extends AbstractClass
{
   protected function
getValue() {
       return
"ConcreteClass1";
   }
}

class
ConcreteClass2 extends AbstractClass
{
   public function
getValue() {
       return
"ConcreteClass2";
   }

}

$class1 = new ConcreteClass1;
$class1->printOut();

$class2 = new ConcreteClass2;
$class2->printOut();
?>

Old code that has no user-defined classes or functions named 'abstract' should run without modifications.



User Contributed Notes
Object Abstraction
mweierophinney at gmail dot com
17-Apr-2005 01:29
If you inherit from an abstract class, any method in the abstract class marked as abstract *must* be implemented by the extending class. For example, in the following abstract class:
<?php
abstract class AbstractClass
{
   public function
setup() {}
   abstract public function
doSomething();
}
?>
the method 'doSomething' must be defined in the extending class. Thus, the following does *not* work:
<?php
class ConcreteClass extends AbstractClass
{
   public function
doMyOwnThing() {}
}
?>
But the following *will*:
<?php
class ConcreteClass extends AbstractClass
{
   public function
doMyOwnThing() {}
   public function
doSomething() {}
}
?>

The lesson to learn here: if the method is truly optional to the implementation, either do not define it in the abstract class at all, or do not tag it as abstract.

<Object ConstantsObject Interfaces>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT