Home Backend Development PHP Problem What is the difference between interface and abstract class in php

What is the difference between interface and abstract class in php

Mar 15, 2021 pm 05:29 PM
php abstract class interface

The difference is: 1. The interface is defined through the interface keyword, and the abstract class is defined through the abstract keyword; 2. The interface has no data members, but the abstract class has data members, and the abstract class can implement Data encapsulation; 3. The interface does not have a constructor, but the abstract class can have a constructor.

What is the difference between interface and abstract class in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

1. Abstract classes and interfaces Difference

When learning PHP object-oriented, people will be confused about abstract classes and interfaces. Why are they so easy to confuse when they have almost the same functions? Why not keep one and leave the other? But in fact, the difference between the two is still very big. If you can make good use of the two methods of PHP, object-oriented programming will be more reasonable, clear and efficient.

a. The interface is defined through the interface keyword, and the abstract class is defined through the abstract keyword.
b. The use of interfaces is achieved through the keyword implements, while the operation of abstract classes is implemented using the keyword extends of class inheritance. Pay special attention when using it.
c. Interfaces have no data members, but abstract classes have data members, and abstract classes can encapsulate data.
d. Interfaces do not have constructors, and abstract classes can have constructors.
e. The methods in the interface are all public types, while the methods in the abstract class can be modified with private, protected or public.
f. A class can implement multiple interfaces at the same time, but can only implement one abstract class.

Same points: Nothing can be written in the function bodies of abstract methods and interfaces, not even two curly brackets! ! ! For example: function getName(); This will do.

2. Interface

Using interface (interface), you can specify which methods a certain class must implement, but it is not required Define the specifics of these methods.

The interface is defined through the interface keyword, just like defining a standard class, but all methods defined in it are empty.

All methods defined in the interface must be public. This is a characteristic of the interface.

Implementations

To implement an interface, use the implements operator. The class must implement all methods defined in the interface, otherwise a fatal error will be reported. A class can implement multiple interfaces. Use commas to separate the names of multiple interfaces.

Note:
When implementing multiple interfaces, methods in the interfaces cannot have the same name.

Note:
Interfaces can also be inherited by using the extends operator.

Note:
To implement an interface, a class must use exactly the same method as the method defined in the interface. Otherwise a fatal error will result.

Constant

Constant can also be defined in the interface. Interface constants are used exactly the same as class constants, but cannot be overridden by subclasses or subinterfaces.

 <?php

// 声明一个&#39;iTemplate&#39;接口
interface iTemplate
{
    public function setVariable($name, $var);
    public function getHtml($template);
}


// 实现接口
// 下面的写法是正确的
class Template implements iTemplate
{
    private $vars = array();

    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }

    public function getHtml($template)
    {
        foreach($this->vars as $name => $value) {
            $template = str_replace('{' . $name . '}', $value, $template);
        }

        return $template;
    }
}

// 下面的写法是错误的,会报错,因为没有实现 getHtml():
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
    private $vars = array();

    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }
}
?>
Example #2 可扩充的接口

<?php
interface a
{
    public function foo();
}

interface b extends a
{
    public function baz(Baz $baz);
}

// 正确写法
class c implements b
{
    public function foo()
    {
    }

    public function baz(Baz $baz)
    {
    }
}

// 错误写法会导致一个致命错误
class d implements b
{
    public function foo()
    {
    }

    public function baz(Foo $foo)
    {
    }
}
?>
Example #3 继承多个接口

<?php
interface a
{
    public function foo();
}

interface b
{
    public function bar();
}

interface c extends a, b
{
    public function baz();
}

class d implements c
{
    public function foo()
    {
    }

    public function bar()
    {
    }

    public function baz()
    {
    }
}
?>
Example #4 使用接口常量

<?php
interface a
{
    const b = &#39;Interface constant&#39;;
}

// 输出接口常量
echo a::b;

// 错误写法,因为常量不能被覆盖。接口常量的概念和类常量是一样的。
class b implements a
{
    const b = &#39;Class constant&#39;;
}
?>
Copy after login

http://php.net/manual/zh/language.oop5.interfaces.php

3. Abstract class

PHP 5 Supports abstract classes and abstract methods. Classes defined as abstract cannot be instantiated. Any class must be declared abstract if at least one method in it is declared abstract. A method defined as abstract only declares its calling method (parameters) and cannot define its specific function implementation.

When inheriting an abstract class, the subclass must define all abstract methods in the parent class; in addition, the access control of these methods must be the same (or more relaxed) as in the parent class. For example, if an abstract method is declared as protected, then the method implemented in the subclass should be declared as protected or public, and cannot be defined as private. In addition, the method calling methods must match, that is, the type and number of required parameters must be consistent. For example, if a subclass defines an optional parameter that is not included in the declaration of an abstract method of the parent class, there is no conflict between the two declarations. This also applies to constructors since PHP 5.4. Constructor declarations before PHP 5.4 could be different.

<?php
abstract class AbstractClass
{
 // 强制要求子类定义这些方法
    abstract protected function getValue();
    abstract protected function prefixValue($prefix);

    // 普通方法(非抽象方法)
    public function printOut() {
        print $this->getValue() . "\n";
    }
}

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

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass1";
    }
}

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

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass2";
    }
}

$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";

$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue('FOO_') ."\n";
?>
以上例程会输出:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2
Example #2 抽象类示例

<?php
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"), "\n";
echo $class->prefixName("Pacwoman"), "\n";
?>
以上例程会输出:

Mr. Pacman
Mrs. Pacwoman
老代码中如果没有自定义类或函数被命名为“abstract”,则应该能不加修改地正常运行。
Copy after login

http://php.net/manual/zh/language.oop5.abstract.php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What is the difference between interface and abstract class in php. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles