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
How to implement hot update of function in PHP?How to implement hot update of function in PHP?May 15, 2025 pm 08:33 PM

There are three ways to implement hot updates for functions in PHP: 1. Rewrite the function and use runkit to dynamically rewrite the function; 2. Use OPcache to realize hot updates by restarting OPcache; 3. Use external tools such as deployer or ansible to automatically deploy and update code.

How to replace elements while iterating through PHP arrays?How to replace elements while iterating through PHP arrays?May 15, 2025 pm 08:30 PM

In PHP, you can use the following methods to traverse and replace array elements: 1. Use a foreach loop and reference (&$value) to modify the elements, but be aware that references may cause side effects. 2. Use a for loop to directly access indexes and values ​​to avoid reference problems. 3. Use the array_map function to make concise modifications, but the key name will be reset. 4. Use the array_walk function to modify the value and retain the key name. Performance, side effects and key name retention requirements should be taken into account when selecting a method.

How to verify ISBN strings in PHP?How to verify ISBN strings in PHP?May 15, 2025 pm 08:27 PM

Verifying ISBN strings in PHP can be implemented through a function that can handle two formats: ISBN-10 and ISBN-13. 1. Remove all non-numeric characters. 2. For ISBN-10, weighted sum calculation is used, and it is valid if the result can be divided by 11. 3. For ISBN-13, different weighting sum calculations are used, and it is valid if the result can be divided by 10. This function returns a Boolean value indicating whether the ISBN is valid.

How to implement automatic loading of classes in PHP?How to implement automatic loading of classes in PHP?May 15, 2025 pm 08:24 PM

In PHP, automatically loading classes are implemented through the __autoload or spl_autoload_register function. 1. The __autoload function has been abandoned, 2. The spl_autoload_register function is more flexible, supports multiple automatic loading functions, and can handle namespace and performance optimization.

How to modify array elements in PHP?How to modify array elements in PHP?May 15, 2025 pm 08:21 PM

Methods to modify array elements in PHP include direct assignment and batch modification using functions. 1. For indexed arrays, such as $colors=['red','green','blue'], the second element can be modified by $colors[1]='yellow'. 2. For associative arrays, such as $person=['name'=>'John','age'=>30], the value of age can be modified by $person['age']=31. 3. Use array_map or array_walk functions to modify array elements in batches, such as $numbers=array_map(fun

How to implement hook function in PHP?How to implement hook function in PHP?May 15, 2025 pm 08:18 PM

Implementing hook functions in PHP can be implemented through observer mode or event-driven programming. The specific steps are as follows: 1. Create a HookManager class to register and trigger hooks. 2. Use the registerHook method to register the hook and trigger the hook by the triggerHook method when needed. Hook functions can improve the scalability and flexibility of the code, but pay attention to performance overhead and debugging complexity.

PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment