PHP에서 추상 클래스는 무엇입니까?
PHP에서 추상 클래스는 무엇입니까?
어떻게 사용할 수 있습니까?
추상 클래스는 하나 이상의 추상 메서드를 포함하는 클래스로, 실제 코드가없는 메서드, 이름과 매개 변수 만 있으며 "추상"으로 표시됩니다.
이것의 목적은 상속 할 템플릿을 제공하고 상속 클래스가 추상 메서드를 구현하도록 강제하는 것입니다.
따라서 추상 클래스는 일반 클래스와 순수 인터페이스 사이에 있습니다. 또한 인터페이스는 모든 메서드가 추상 인 추상 클래스의 특수한 경우입니다.
자세한 내용 은 PHP 매뉴얼 의이 섹션 을 참조하십시오.
추상 클래스는 하나 이상의 추상 메서드를 포함하는 클래스입니다. 추상 메서드는 선언되었지만 구현이없는 메서드입니다. 추상 클래스는 인스턴스화되지 않을 수 있으며 추상 메서드에 대한 구현을 제공하기 위해 하위 클래스가 필요합니다.
1. 추상 클래스를 인스턴스화 할 수 없음 : 추상으로 정의 된 클래스는 인스턴스화 할 수 없으며 적어도 하나의 추상 메소드를 포함하는 클래스도 추상이어야합니다.
아래 예 :
abstract class AbstractClass
{
abstract protected function getValue();
abstract protected function prefixValue($prefix);
public function printOut() {
echo "Hello how are you?";
}
}
$obj=new AbstractClass();
$obj->printOut();
//Fatal error: Cannot instantiate abstract class AbstractClass
2. 하나 이상의 추상 메서드를 포함하는 모든 클래스는 추상이어야합니다 . 추상 클래스는 추상 및 비추 상 메서드를 가질 수 있지만 적어도 하나의 추상 메서드를 포함해야합니다. 클래스에 하나 이상의 추상 메서드가있는 경우 해당 클래스는 추상으로 선언되어야합니다.
참고 : 특성은 전시 클래스에 요구 사항을 부과하기 위해 추상 메서드 사용을 지원합니다.
아래 예 :
class Non_Abstract_Class
{
abstract protected function getValue();
public function printOut() {
echo "Hello how are you?";
}
}
$obj=new Non_Abstract_Class();
$obj->printOut();
//Fatal error: Class Non_Abstract_Class contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Non_Abstract_Class::getValue)
3. 추상 메서드는 본문을 포함 할 수 없습니다 . 추상으로 정의 된 메서드는 단순히 메서드의 서명을 선언합니다. 구현을 정의 할 수 없습니다. 그러나 비 추상적 인 방법으로 구현을 정의 할 수 있습니다.
abstract class AbstractClass
{
abstract protected function getValue(){
return "Hello how are you?";
}
public function printOut() {
echo $this->getValue() . "\n";
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";
//Fatal error: Abstract function AbstractClass::getValue() cannot contain body
4. 추상 클래스에서 상속 할 때 부모의 클래스 선언에서 abstract로 표시된 모든 메서드는 자식에 의해 정의되어야합니다 . 추상 클래스를 상속하는 경우 그 안에있는 모든 추상 메서드에 구현을 제공해야합니다.
abstract class AbstractClass
{
// Force Extending class to define this method
abstract protected function getValue();
// Common method
public function printOut() {
print $this->getValue() . "<br/>";
}
}
class ConcreteClass1 extends AbstractClass
{
public function printOut() {
echo "dhairya";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
//Fatal error: Class ConcreteClass1 contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (AbstractClass::getValue)
5. 동일하거나 덜 제한적인 가시성 : 추상 클래스에서 상속 할 때 부모의 클래스 선언에서 추상으로 표시된 모든 메서드는 자식에 의해 정의되어야합니다. 또한 이러한 메서드는 동일하거나 덜 제한된 가시성을 사용하여 정의해야합니다. 예를 들어, 추상 메서드가 protected로 정의 된 경우 함수 구현은 private이 아닌 protected 또는 public으로 정의되어야합니다.
추상 메서드는 비공개가 아니어야합니다.
abstract class AbstractClass
{
abstract public function getValue();
abstract protected function prefixValue($prefix);
public function printOut() {
print $this->getValue();
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."<br/>";
//Fatal error: Access level to ConcreteClass1::getValue() must be public (as in class AbstractClass)
6. Signatures of the abstract methods must match:When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child;the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. For example, if the child class defines an optional argument, where the abstract method's signature does not, there is no conflict in the signature.
abstract class AbstractClass
{
abstract protected function prefixName($name);
}
class ConcreteClass extends AbstractClass
{
public function prefixName($name, $separator = ".") {
if ($name == "Pacman") {
$prefix = "Mr";
} elseif ($name == "Pacwoman") {
$prefix = "Mrs";
} else {
$prefix = "";
}
return "{$prefix}{$separator} {$name}";
}
}
$class = new ConcreteClass;
echo $class->prefixName("Pacman"), "<br/>";
echo $class->prefixName("Pacwoman"), "<br/>";
//output: Mr. Pacman
// Mrs. Pacwoman
7. Abstract class doesn't support multiple inheritance:Abstract class can extends another abstract class,Abstract class can provide the implementation of interface.But it doesn't support multiple inheritance.
interface MyInterface{
public function foo();
public function bar();
}
abstract class MyAbstract1{
abstract public function baz();
}
abstract class MyAbstract2 extends MyAbstract1 implements MyInterface{
public function foo(){ echo "foo"; }
public function bar(){ echo "bar"; }
public function baz(){ echo "baz"; }
}
class MyClass extends MyAbstract2{
}
$obj=new MyClass;
$obj->foo();
$obj->bar();
$obj->baz();
//output: foobarbaz
Note: Please note order or positioning of the classes in your code can affect the interpreter and can cause a Fatal error. So, when using multiple levels of abstraction, be careful of the positioning of the classes within the source code.
below example will cause Fatal error: Class 'horse' not found
class cart extends horse {
public function get_breed() { return "Wood"; }
}
abstract class horse extends animal {
public function get_breed() { return "Jersey"; }
}
abstract class animal {
public abstract function get_breed();
}
$cart = new cart();
print($cart->get_breed());
An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.
There is good explanation of that here.
Abstract Class
1. Contains an abstract method
2. Cannot be directly initialized
3. Cannot create an object of abstract class
4. Only used for inheritance purposes
Abstract Method
1. Cannot contain a body
2. Cannot be defined as private
3. Child classes must define the methods declared in abstract class
Example Code:
abstract class A {
public function test1() {
echo 'Hello World';
}
abstract protected function f1();
abstract public function f2();
protected function test2(){
echo 'Hello World test';
}
}
class B extends A {
public $a = 'India';
public function f1() {
echo "F1 Method Call";
}
public function f2() {
echo "F2 Method Call";
}
}
$b = new B();
echo $b->test1() . "<br/>";
echo $b->a . "<br/>";
echo $b->test2() . "<br/>";
echo $b->f1() . "<br/>";
echo $b->f2() . "<br/>";
Output:
Hello World
India
Hello World test
F1 Method Call
F2 Method Call
- Abstract Class contains only declare the method's signature, they can't define the implementation.
- Abstraction class are defined using the keyword abstract .
- Abstract Class is not possible to implement multiple inheritance.
- Latest version of PHP 5 has introduces abstract classes and methods.
- Classes defined as abstract , we are unable to create the object ( may not instantiated )
Abstract Classes are those classes which can not be initialised directly. Or in other word we can say that abstract classes are those classes which object can not be created directly. In PHP abstract classes are defied with keyword abstract.
Also to become one class abstract ateast one method of the class must be abstract.
For the detail of the abstract class you can refer to my blog on Abstract Class in PHP.
An abstract class is like the normal class it contains variables it contains protected variables functions it contains constructor only one thing is different it contains abstract method.
The abstract method means an empty method without definition so only one difference in abstract class we can not create an object of abstract class
Abstract must contains the abstract method and those methods must be defined in its inheriting class.
참고URL : https://stackoverflow.com/questions/2558559/what-is-an-abstract-class-in-php
'programing tip' 카테고리의 다른 글
풀하기 전에 로컬과 github의 차이점을 확인하는 방법 (0) | 2020.08.11 |
---|---|
자바 스크립트 i ++ 대 ++ i (0) | 2020.08.11 |
NSLayoutConstraint가 ViewController를 충돌시킵니다. (0) | 2020.08.11 |
html에서 클릭 한 요소 주변의 점선을 제거하는 방법 (0) | 2020.08.11 |
MySQL 루트 사용자의 전체 권한을 어떻게 복원 할 수 있습니까? (0) | 2020.08.11 |