Home Backend Development PHP Tutorial How to use PHP's function variable array to change the code structure (with examples)

How to use PHP's function variable array to change the code structure (with examples)

Oct 16, 2018 pm 04:22 PM
php

The content of this article is about how to use PHP’s function variable array to change the code structure (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

The project gets bigger and bigger, the code becomes more and more messy, and maintenance is difficult. There are many reasons. At first, in order to realize the function, we did not pay attention to the structure of the code, it was an outsourcing company. Although the company's project leader has been considering reuse and encapsulation, I feel that the desired effect has not been achieved. Because design patterns are not used in the entire code, this structure is definitely not much better. Although many functions are encapsulated, the layering is particularly messy, and it feels like encapsulation for the sake of encapsulation. In fact, I don’t understand many things, but after writing the code, I will occasionally slightly modify the structure of the code, so as to dig as few holes for myself as possible.

Problems with code structure

The interface has a large number of methods. When calling the interface, you need to use switch to make a judgment. The general structure is as follows:

private function makeXML($xmlName, $xmlNameParam)
{
    $requestData = null;
    switch ($xmlName) {
        // ...
        case 'sendOrder':
            $requestData = $this->sendOrder($xmlNameParam);
            break;
        case 'ecfareQuery':
            $requestData = $this->ecfareQuery($xmlNameParam);
            break;
        case 'getInterAV':
            $requestData = $this->getInterAV($xmlNameParam);
            break;
        // ...
    }
    
    return $requestData;
}
Copy after login

The above case The corresponding methods are called to splice the XML information required by the interface. The parameters of the

method pass the name and parameters of the splicing interface method respectively.

Such a judgment structure code feels difficult to manage. To add a method, you need to add a case call, and it is also messy when you look at it.

Improvement of code structure

Therefore, relevant improvements have been made. The improvements are as follows:

1. First define a method array for saving The method name is defined as follows

protected $arr = [];
public function __construct()
{
    // 初始化接口方法
    $this->arr = [
        'getAV'                    => 'getAV',
        'sendOrder'                => 'sendOrder',
        'ecfareQuery'              => 'ecfareQuery',
        'getInterAV'               => 'getInterAV',
        // ...
    ];
}
Copy after login

If there are new methods under this interface in the future, just add them directly to the array. This saves a lot of switch case judgments.

2. Modify the structure of switch. The code is as follows:

private function makeXML($xmlName, $xmlNameParam)
{
    $requestData = null;
    
    $fun = $this->arr[$xmlName];
    
    $requestData = $this->$fun($xmlNameParam);
    
    return $requestData;
}
Copy after login

Change the structure of switch case to the method of calling by array subscript. In this way, all methods are managed uniformly.

The above ideas come from the MFC framework's processing of Windows messages.

Equivalent to an array of function pointers in C language, or a delegate in C#.

Knowledge supplement:

Process-oriented function variables (look up)

function come() {                   //定义com函数
  echo "来了<p>";
}
function go($name = "jack") {       //定义go函数
  echo $name."走了<p>";
}
function back($string)              //定义back函数
{
  echo "又回来了,$string<p>";
}
$func = "come";                     //声明一个变量,将变量赋值为“come”
$func();                            //使用变量函数来调用函数come()
$func = "go";                       //重新给变量赋值
$func("Tom");                       //使用变量函数来调用函数go()
$func = "back";                     //重新给变量赋值
$func("Lily");                      //使用变量函数来调用函数back();
Copy after login

The object-oriented method in PHP is as follows (implement it by yourself ):

<?php
class test
{
    public $arr = [];
    
    public function __construct()
    {
        $this->arr = array(
            &#39;func1&#39;=>&#39;func1&#39;,
            &#39;func2&#39;=>&#39;func2&#39;,
            &#39;func3&#39;=>&#39;func3&#39;,
            &#39;func4&#39;=>&#39;func4&#39;,
            &#39;func5&#39;=>&#39;func5&#39;,
        );
    }
    public function submit($func, $str)
    {
        $f = $this->arr[$func];
        $this->$f($str);
    }
    static public function func1($str)
    {
        print &#39;func1&#39; . &#39; &#39; . $str . "\n";
    }
    static public function func2($str)
    {
        print &#39;func2&#39; . &#39; &#39; . $str . "\n";
    }

    public function func3($str)
    {
        print &#39;func3&#39; . &#39; &#39; . $str . "\n";
    }
    private function func4($str)
    {
        print &#39;func4&#39; . &#39; &#39; . $str . "\n";
    }
    private function func5($str)
    {
        print &#39;func5&#39; . &#39; &#39; . $str . "\n";
    }
}
$t = new test();        // 实例化类
$f = $t->arr[&#39;func1&#39;];
test::$f(&#39;abc&#39;);        // func1 func2 是静态方法
$f = $t->arr[&#39;func2&#39;];
test::$f(&#39;abc&#39;);
$f = $t->arr[&#39;func3&#39;];  // func3 的调用
$t->$f(&#39;abc&#39;);
// func4 func5 的调用需要使用 submit 方法进行分发
$t->submit(&#39;func4&#39;, &#39;abc&#39;);
$t->submit(&#39;func5&#39;, &#39;bcd&#39;);
Copy after login

The output of the above code is as follows:

func1 abc
func2 abc
func3 abc
func4 abc
func5 bcd
Copy after login

The above is the detailed content of How to use PHP's function variable array to change the code structure (with examples). 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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

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

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

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

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles