Backend Development
PHP Tutorial
Let's talk about the basics of object-oriented programming in PHP (2)Let's talk about the basics of object-oriented programming in PHP (2)
This article mainly talks about the foundation of PHP object-oriented programming (2). It has certain learning value. Interested friends can learn about it.
In some small projects, you will frequently come into contact with the inheritance, encapsulation, polymorphism and other features of classes, and use the functions of the class itself.
But in large projects, class interfaces are often used for implementation, because interfaces do not involve the implementation of specific functions of the class, but interfaces will limit the functions of the class.
A complex and large-scale software needs to be composed of numerous functional classes. These functional classes need to be completed by multiple programmers. Among them, the software architect needs to specify the involved mode, team division of labor and other tasks.
This brings about the problem of programming unity. How to ensure that key functions can be well implemented requires a design interface that can take into account all aspects. Class interfaces are usually used, although PHP can use many method.
Features such as encapsulation, foundation, and polymorphism of classes all involve the functions of classes, which are generally implemented in small projects using class functions.
But in large-scale projects, the software needs to have many functions, which requires many functional classes, and these functional classes are usually completed by multiple programmers, so among the many programmers, The problem of unified programming arises. How to ensure that the functions of the software can be well realized?
This requires defining a set of functions in advance before software design, and then programmers implement these functions one by one.
There are many methods that can be used in PHP, usually implemented using class interfaces. A set of functions is defined in the interface, but the implementation of the functions requires programmers to implement them one by one, thus ensuring the integrity of the software functions.
1. Definition of interface
The interface is not a functional class, so specific function implementation methods cannot be defined in the interface class.
Use the interface keyword when defining an interface. The naming format is: I interface name.
Usually the members defined in the interface must be methods of the functional class and cannot be member attributes of the functional class.
A few points to note:
① Interface members must have global access permissions, so access modifiers cannot be added;
② Interface members cannot use constants, static methods, etc. Properties;
③Interface members cannot define constructors.
④Interfaces can be inherited like classes. After inheritance, the sub-interface will get all the members of the parent interface.
2. Implementation of interface
Interfaces can only define functions, but cannot implement specific functions. If you want to realize the functions defined in the interface, you must use ordinary functional classes to implement them.
Format: implements interface name
Note: All member methods in the interface must be defined in the functional class, and no one can be left out.
The following is demonstrated through a simple example
In the interface file, define two interfaces Imyinterce, Imys (Imyinterface sub-interface)
<?php
/**
* 定义接口Imyinterface
*/
interface Imyinterface{
function add1();
function add2($s);
function add3($t=0);
}
//接口的继承
interface Imys extends Imyinterface{
function del();
function edit();
function update($str);
function select($id,$str);
}
?>Then define a functional class to implement the interface. If you haven't figured out how to implement the function, you can implement it through an empty method. It cannot be omitted, otherwise an error will be reported, indicating that the functional class contains an abstract method, which must be implemented.
Only the update and select methods in the sub-interface Imy are implemented here. The other methods have not been implemented yet, and empty methods are used instead.
<?php
require "./Imyinterface.interface.php";
class MyClass implements Imys{
function add1(){
//空方法,暂无具体实现方法,虽然功能类继承Imys,但是接口Imys又继承Imyinterface,因此Imyinterface里的方法也必须要实现
}
function add2($str){
//同上
}
function add3($t=0){
//同上
}
function del(){
//空方法,暂无具体实现方法
}
function edit(){
//空方法,暂无具体实现方法
}
function update($str="字符串"){
return $str;
}
function select($id=0,$str="字符串"){
return $id.$str;
}
}
?>Test code
<?php
require "./MyClass.class.php";
header("Content-type:text/html;charset=utf-8");
$mys =new MyClass();
echo $mys->select();
?>Browse effect

The above introduces the process of standardizing and unifying procedures in large-scale software design , usually using interfaces. However, the interface can only define the abstract functions of the program, but does not provide specific functions. Ordinary class members, such as constants, static properties and other ordinary members cannot be defined in the interface.
Abstract classes are designed for class inheritance. Ordinary class members can be defined in abstract classes. At this point, abstract classes are much more flexible than interfaces.
When defining an abstract class, you need to add the abstract keyword, and then define ordinary member methods in the abstract class. This ordinary method does not require specific function code.
Most MVC frameworks are built using PHP abstract classes. Abstract classes can be simply understood as a combination of ordinary classes and interfaces, that is, abstract=class interface.
Common points between interfaces and abstract classes:
① Neither interfaces nor abstract classes can be instantiated. Interfaces need to be implemented using the implements keyword, while abstract classes use the extends keyword of ordinary classes to inherit. .
② Both interfaces and abstract classes contain method declarations that have not yet been implemented.
③ Derived classes must implement unimplemented methods. Abstract classes are abstract methods, and interfaces are all members.
The difference between interfaces and abstract classes:
①Abstract classes cannot be sealed, but interfaces can.
②Concrete methods implemented by abstract classes are virtual by default, but class methods that implement interfaces are real by default.
③The abstract class must list all members in the base class list of the class so that the implementation class can implement it, but the interface allows empty methods.
After understanding the concepts of interfaces and abstract classes, let’s take a closer look at the definition and implementation of abstract classes.
在PHP中,抽象类不能为空类或普通类,至少需要提供一个抽象方法,而抽象类和抽象方法都需要关键字abstract。
例如,定义一个简单的CURD抽象类(数据库的增删改查)
<?php
/**
* 抽象类的定义
*/
abstract class BaseClass{
//查询,抽象方法
abstract function query($sql);
//插入,抽象方法
abstract function insert($sql);
//更新,抽象方法
abstract function update($sql);
//删除,抽象方法
abstract function delete($sql);
//数据库连接,普通类方法
protected $link;
//sql语句
protected $sql;
//结果
protected $arr;
protected function Conn(){
$this->link=mysql_connect("localhost","root","123") or die("数据库连接失败").mysql_error();
if($this->link){
mysql_select_db("db_match",$this->link) or die("数据库选择失败").mysql_error();
}
return $this->link;
}
//关闭数据库连接,普通类方法
protected function CloseConn(){
mysql_close($this->link);
}
}
?>抽象类的实现
<?php
require "./BaseClass.class.php"; //引入抽象类
/**
* 实现抽象类
*/
class MyClass extends BaseClass {
//实现抽象中的抽象方法,抽象类中抽象方法:query()、insert()、update()、delete()
function query($sql){
$this->Conn($this->link);
$this->sql=$sql;
$result=mysql_query($this->sql);
while($row=mysql_fetch_assoc($result)){
$this->arr=$row;
}
$this->CloseConn($this->link); //关闭连接
return print_r($this->arr);
}
function insert($sql){
$this->Conn($this->link);
$this->sql=$sql;
mysql_query($this->sql,$this->link);
$this->CloseConn($this->link); //关闭连接
}
function update($sql){
$this->Conn($this->link);
$this->sql=$sql;
mysql_query($this->sql,$this->link);
$this->CloseConn($this->link); //关闭连接
}
function delete($sql){
$this->Conn($this->link);
$this->sql=$sql;
mysql_query($this->sql,$this->link);
$this->CloseConn($this->link); //关闭连接
}
}
?>测试代码
<?php
require "./MyClass.class.php";
header("Content-type:text/html;charset=utf-8");
$mys =new MyClass();
$mys->query("select * from `match`");
//输出结果:Array ( [m_id] => 8 [t1_id] => 5 [t2_id] => 6 [t1_score] => 2 [t2_score] => 1 [m_time] => 1421571600 )
$mys->insert("insert into `match`(m_id,t1_id,t2_id,t1_score,t2_score,m_time) values(9,5,3,3,3,1451571600)");
//添加成功
$mys->update("update `match` set m_time =1111111111 where m_id=9");
//修改成功
$mys->delete("delete from `match` where m_id=9");
//删除成功
?>相关教程:PHP视频教程
The above is the detailed content of Let's talk about the basics of object-oriented programming in PHP (2). For more information, please follow other related articles on the PHP Chinese website!
PHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AMPHP 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.
PHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AMPHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.
Choosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AMPHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.
PHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AMPHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.
PHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AMPHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AMPHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.
How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AMIn PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.
PHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AMPHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment





