Table of Contents
简单理解PHP的面向对象编程方式,php面向对象编程
Home php教程 php手册 简单理解PHP的面向对象编程方式,php面向对象编程

简单理解PHP的面向对象编程方式,php面向对象编程

Jun 13, 2016 am 08:39 AM
php programming language object-oriented

简单理解PHP的面向对象编程方式,php面向对象编程

与大多数可以面向对象的编程语言不一样, PHP 是同时支持面向过程和面向对象的编程方式, PHP 开发者可以在面向过程和面向对象二者中自由选择其一或是混合使用,不过由于在 PHP5 之前的版本中, PHP 主要还是面向过程的编程语言,因此大多时候 PHP 开发者应该还是选择面向过程的方式进行开发,事实上, Kayo 认为即使一个 PHP 开发者完全不使用面向对象,他也能开发出很出色的 PHP 程序,我们可以想象, Web 页面的解析本身就很过程化,在 HTML 中嵌入面向过程处理的代码是非常自然的手段,因此不能说面向对象是一种比面向过程更加优秀的编程方式,只是另一种编程选择,当然这里说的是 PHP 中的情况。

对于 PHP 中面向过程和面向对象各自的优缺点,相信在网上稍查一下就会很清楚了,面向过程开发周期短,发布快,效率较高,面向对象开发周期长,效率较低但易于维护,改进,扩展和开发 API 。显然易见,我们很难说哪一个方式会更优秀,与其争论哪一种编程方式更优秀,不如尽量发挥出两种编程方式各自的优势。

回到 PHP 的面向对象编程,在使用面向对象的过程中还是很容易就感受到它的优势,最明显的地方是代码功能更加清晰,数据处理,用户登陆,内容呈现等各写成一个类,在页面中只需包含这些类、实例化对象,然后再用简洁的语句应用对象就行,这与面向过程中把数据处理,用户登陆,还有内容等部分写在一起相比,前者的编程思路肯定更加清晰和易于理解,相信团队开发中应该更为偏向于面向对象编程。

下面举一个简单的例子说明一下面向过程和面向对象两种方式各自的优缺点

在处理表单或接受 url 参数时,为了防止 SQL 注入等问题, PHP 开发者常常需要过滤字符串。

在面向过程的方式中,我们会在需要过滤字符串的语句中调用各种过滤字符串的库函数或自定义函数,这样下来,页面中就会出现很多不同的过滤函数甚至还有复杂的正则表达式,即使在页面中写了足够的注释难免还是比较混乱,下面看看面向对象的处理方式。

首先是定义了一个简单的处理字符串的类,把各种复杂的字符串处理写成方法(关于 PHP 面向对象的知识可以 Google ,本文不另外叙述。)

<&#63;php 
/* 字符串处理类
 * 参数$length用作判断字符串是否超过指定长度
 * 转义 SQL 语句中使用的字符串中的特殊字符
 * 正则限制字符串内只能为数字
 * 判断字符串是否为空
 * 判断字符串长度
 
*/
 
// 创建字符串处理类
class StringFiltration {
 
  // 属性
  var $length;
 
  // 方法
  // 构造方法
  function __construct($the_length = NULL){
    $this->length = $the_length;
  }
  // 转义 SQL 语句中使用的字符串中的特殊字符
  function realEscapeString($the_string){
    return mysql_real_escape_string($the_string);
  }
   
  // 正则限制字符串内只能为数字
  function eregNumber($the_string){
    if( ereg("^[0-9]+$",$the_string) )
      return true;
    else
      return false;
  }
   
  // 判断字符串是否为空
  function strlenString($the_string){
    return strlen($the_string);
  }
   
  // 判断字符串长度
  function ifOverStrlenLength($the_string){
    if( strlen($the_string) > $this->length )
      return true;
    else
      return false;
  }
 
}
 
&#63;>

Copy after login

然后在需要过滤字符串的页面中实例化该类

$string = new StringFiltration(); 
Copy after login

接着在过滤或判断字符串时调用类中定义好的方法,于是页面中会出现一些调用方法的语句。

$email = $string->realEscapeString($_POST['email']);
$postId = $string->eregNumber($id);
Copy after login

 
在上面的例子中,我们可以看到,在面向对象处理字符串之前,我们必须定义一个类,然后再在需要的页面中实例化这个类并调用这个类中的方法,这里看来,面向对象的效率相比面向过程是低了,而且也很麻烦,不过这样的优势也很明显,实际处理或判断字符串的语句都写在类的内部,在调用方法的页面并不会出现各种复杂的自定义函数和诸如正则表达式这样复杂的语句,页面的结构乃至整个网站的结构更加清晰了,并且在写好一个类后,日后进行 PHP 开发时都可以再使用这个类,从长远来看效率反而高了。因此一直都在进行 PHP 面向过程编程的开发者不妨换种思路,试试面向对象。

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

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

See all articles