Abstract Class in php
Cảnh báo Spam: Bài đăng này chưa sẵn sàng để xuất bản. Tác giả có thể đã vô tình công khai nó trong quá trình viết. Do đó, bạn nên suy nghĩ trước khi đọc bài bài này.
➔ PHP 5 incorporates the concept of abstract classes and abstract methods.
➔ The abstract class defined is not intended to be used to create an object from it; the abstract class has at least one abstract method that must be initialized to mean an abstract class.
➔ Abstract methods only declare the method name and parameter list (method signature), but do not define the inner executable (nobody like interface methods).
Inherit the abstract class
➔ When a class inherits an abstract class, it must define (implement) all abstract methods in the abstract class that it inherits.
➔ In addition, methods must have the same visibility level defined or higher than the specified visibility in the parent class (public, private, protected)
Example
➔ AbstractClass abstract class definition
<?php
abstract class AbstractClass
{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);
// Common method
public function printOut()
{
print $this->getValue() . "\n";
}
}
?>
➔ Creates a ConcreteClass1 child class inheriting AbstractClass
<?php
class ConcreteClass1 extends AbstractClass
{
protected function getValue()
{
return "ConcreteClass1";
}
public function prefixValue($prefix)
{
return "{$prefix}ConcreteClass1";
}
}
?>
➔ Creates a ConcreteClass2 child class inheriting AbstractClass
<?php
class ConcreteClass2 extends AbstractClass
{
protected function getValue()
{
return "ConcreteClass2";
}
public function prefixValue($prefix)
{
return "{$prefix}ConcreteClass2";
}
}
?>
➔ Creates $class1 $class2 object
<?php
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue("Foo_") . "\n";
$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue("Foo_") . "\n";
?>
➔ Show result
ConcreteClass1
Foo_ConcreteClass1
ConcreteClass2
Foo_ConcreteClass2
All rights reserved