search
HomeBackend DevelopmentPHP TutorialAbstract Class and Interface in PHP_PHP Tutorial

Abstract Class and Interface in PHP

I recently started learning PHP MySQL. Let’s record the key points in the learning process, and then consider writing a series of blogs on the process of developing the website.

This blog mainly introduces the difference between Abstract Class and Interface.

Abstract Class

What is Abstract Class

The same as the concept of abstract class in C, a class containing pure virtual function (called abstract method in Java and Php) is called Abstract Class. We sometimes call abstract Class base class, because base class cannot directly generate objects.

Abstract Class in PHP

Let’s look at the code:

abstract class abc
{
public function xyz()
{
return 1;
}
}
$a = new abc();//this will throw error in php

The abstract class in PHP is the same as other oop languages. We use the keyword abstract to declare an abstract class. If you want to directly generate an object of this class, an error will be reported.

abstract class testParent
{
public function abc()
{
//body of your funciton
}
}
class testChild extends testParent
{
public function xyz()
{
//body of your function
}
}
$a = new testChild();

testChild inherits the abstract class testParent through the keyword extends, and then we can generate a testChild object.

Implement Abstract Method

Similar to pure virtual functions in C, we can only declare Abstract method in abstract classes, and we can only and must define it in subclasses.

Actually, this statement is not absolute, but for the convenience of memory, most textbooks say this. Let’s review the explanation of pure virtual functions in Effective C .

"Pure Virtual functions must be redeclared in the derived class, but they can also have their own implementation"

class Airplane{
public:
    virtual void fly(const Airport& destination) = 0;
    ....
};

void Airplane::fly(const Airport& destination){
    // 缺省行为,将飞机飞到指定的目的地
}
class ModelA: public Airplane{
public:
    virtual void fly(const Airport& destination)
    {Airplane::fly(destination);}
    ....
};

class ModelB: public Airplane{
public: 
    virtual void fly(const Airport& destination);
    ....
};
void ModelB:: fly(const Airport& destination){
    // 将C型飞机飞到指定的地方
}
In fact, we made an inline call to the virtual method in derived class ModelA.

The fly I want to be in is divided into two basic elements:

The declaration part represents the interface (which this derived class must use)

The definition part reflects the default behavior (that derived classes may use, but only if they explicitly request it)


The above content is excerpted from "Effective C 55 Specific Practices to Improve Programming and Design" Item 34: Distinguish between interface inheritance and implementation inheritance

Let’s come back and continue discussing the implementation of abstract method in PHP.

abstract class abc
{
abstract protected function f1($a , $b);
}
class xyz extends abc
{
protected function f1($name , $address)
{
echo $name , $address;
}
}
$a = new xyz();

In abc, we declare an abstract method f1 using the keyword abstract. In PHP

Once you declare an abstract method in an abstract class, all subclasses that inherit this class must declare this method , otherwise, PHP will report an error.

abstract class parentTest
{
abstract protected function f1();
abstract public function f2();
//abstract private function f3(); //this will trhow error
}
class childTest
{
public function f1()
{
//body of your function
}
public function f2()
{
//body of your function
}
protected function f3()
{
//body of your function
}
}
$a = new childTest();

As you can see from the above code, declaring a private abstract method will report an error because the private method can only be used in the current class.

Notice that the f1 function is protected in the abstract class, but we can declare it as public in the subclass. no any visibility is less restricted than public.

Interface

Interface in oop enforce definition of some set of method in the class.

Interface will force users to implement some methods. For example, if there is a class that requires set ID and Name attributes, then we can declare this class as an interface, so that all derived classes that inherit from this class will be forced to implement the setId and setName operations

Interface in php

Interface abc
{
public function xyz($b);
}

Like other oop languages, we use the keyword Interface to declare it.

In this interface we declare a method xyz, thenAny time, such a method xyz

must be declared in the subclass

class test implements abc
{
public function xyz($b)
{
//your function body
}
}

You can use the keyword implements to inherit from interface.

In the interface, you can only use public, but not protected and private

interface template1
{
public function f1();
}
interface template2 extends template1
{
public function f2();
}
class abc implements template2
{
public function f1()
{
//Your function body
}
public function f2()
{
//your function body
}
}
You can use the extends keyword to inherit interface, just like a class.

The template2 here will contain all the attributes of template1, so in the implements class abc of template2, you will have to implement function f1 and f2,


You can also extend multiple interfaces:

interface template1
{
public function f1();
}
interface template2
{
public function f2();
}
interface template3 extends template1, template2
{
public function f3();
}
class test implements template3
{
public function f1()
{
//your function body
}
public function f2()
{
//your function body
}
public function f3()
{
//your function body
}
}

At the same time, your class can also implement multiple interfaces

interface template1
{
public function f1();
}
interface template2
{
public function f2();
}
class test implments template1, template2
{
public function f1()
{
//your function body
}
public function f2()
{
//your function body
}
}

But if two interfaces contain methods with the same name, your class will not be able to implement them at the same time.

Methods inherited from interface must have the same parameter specifications . For example, the following code is feasible:

interface template1
{
public function f1($a)
}
class test implements template1
{
public function f1($a)
{
echo $a;
}
}

But code like this will error:

interface template1
{
public function f1($a)
}
class test implements template1
{
public function f1()
{
echo $a;
}
}

However, we do not need to name the parameters in the two methods with the same name. The following code is feasible:

interface template1
{
public function f1($a)
}
class test implements template1
{
public function f1($name)
{
echo $name;
}
}

同时,如果使用default value,你还可以改变参数的default value,下面的代码是可行的:

 

 

interface template1
{
public function f1($a = 20)
}
class test implements template1
{
public function f1($name  = ankur)
{
echo $name;
}
}


 

Abstract Class和Interface之间的不同:

1. In abstract classes this is not necessary that every method should be abstract. But in interface every method is abstract.

在Abstract class中并非所有的method都必须是抽象的,但是在interface中所有的method都自动成为抽象的。就是在子类中必须声明和实现

2. Multiple and multilevel both type of inheritance is possible in interface. But single and multilevel inheritance is possible in abstract classes.

multiple和multilevel inheritance,我不知道改怎么翻译更好,multiple inheritance意思是 在interface中,一个class可以同时implements好多个interface;但是在abstract classes中,只能extends一个class。

当然你extends的这个class可能又extentds别的class,这就是所谓的multilevel inheritance。

3. Method of php interface must be public only. Method in abstract class in php could be public or protected both.

interface中的method必须是public的,但是在abstract class中可以是public或者protected。

4. In abstract class you can define as well as declare methods. But in interface you can only defined your methods.

在abstract class中你可以同时声明(declare)和定义(define)methodes,但是在interface中你只能定义那个methods

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/998009.htmlTechArticlePHP中的Abstract Class和Interface 最近开始学习 PHP+MySQ L,记录下学习过程中的重点内容吧,然后考虑把开发网站的过程也写一个系列Blog。 这篇...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to Register and Use Laravel Service ProvidersHow to Register and Use Laravel Service ProvidersMar 07, 2025 am 01:18 AM

Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.