Home > Backend Development > PHP Tutorial > PHP extension development: developing our own mathematical function library

PHP extension development: developing our own mathematical function library

不言
Release: 2023-03-23 18:32:01
Original
1689 people have browsed it

The content of this article is to share with you the development of PHP extension and the development of our own mathematical function library, which has a certain reference value. Friends in need can refer to it

PHP extension is an advanced PHP program One of the skills that developers must understand. For a beginning PHP extension developer, how can he develop a mature extension and enter the advanced field of PHP development? This series of development tutorials will take you step by step from entry to advanced stages.
This tutorial series is developed under Linux (centos is recommended), the PHP version is 5.6, and it is assumed that you have certain Linux operating experience and C/C foundation.
If you have any questions and need to communicate, please join the QQ technical exchange group 32550793 to communicate with me.

The previous chapter demonstrated a hello world extension. Everyone basically understood the basic style of the extended C source code developed with PHP-CPP. Let's develop a simple mathematical operation library (mymath) to familiarize ourselves with how to export various interface functions.
The code of mymath mathematics library has been placed on github. You can download it directly from git or open the web page in your browser to download the source code.

git download command line

git clone https://github.com/elvisszhang/phpcpp_mymath.git
Copy after login

The browser download URL is the same as the warehouse URL: https://github.com/elvisszhan...

1. Without parameters, How to write an extension function without a return value

Function function: print prime numbers within 100

Function name: mm_print_pn_100

How to register an extension function

Must be in get_module In the function body, register the function mm_print_pn_100 so that it can be called directly in PHP.

PHPCPP_EXPORT void *get_module() 
{
        // 必须是static类型,因为扩展对象需要在PHP进程内常驻内存
        static Php::Extension extension("mymath", "1.0.0");
        
        //这里可以添加你要暴露给PHP调用的函数
        extension.add<mm_print_pn_100>("mm_print_pn_100");
        
        // 返回扩展对象指针
        return extension;
}
Copy after login

The function declaration and code are as follows.
The function does not require parameters. There is no need to put anything in the parameter list of the function, just leave it empty. The function does not need to return a value, and the return value type is set to void.

//打印100以内的素数
void mm_print_pn_100()
{
    int x = 2;
    int y = 1;
    int line = 0;
    while (x <= 100){
        int z = x - y; //z随y递减1
        int a = x%z; //取余数
        if (a == 0) { //如果x被z整除
            if (z == 1) {//如果z为1(x是质数)
                Php::out << x << " ";//输出x
                line ++;//每行输出的数的数量加1
             }
            x ++; //x加1
            y = 1;//y还原
        }
        else {//如果没有被整除
            y ++;//y加1,下一次循环中z减1
        }
        if (line == 10) {//每输出10个数 
            Php::out << std::endl;//输出一个换行        
            line = 0;//还原line
        }
    }
    if (line != 0) //最后一行输出换行
        Php::out << std::endl;
    Php::out.flush();
}
Copy after login

PHP test code

<?php
//打印100以内的素数
mm_print_pn_100();
Copy after login

Run the above PHP code, the output result is

2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97
Copy after login

2. How to write the extension function without parameters and return value

Function function: Calculate the sum of 1, 2, 3, ..., 100
Function name: mm_sum_1_100

Register function mm_sum_1_100, the registration method is the same as the previous section

extension.add<mm_sum_1_100>("mm_sum_1_100");
Copy after login

Function declaration and code show as below.
The function does not require parameters, just set the function parameter list to empty.
The function has a return value, and the return value type is set to Php::Value. Since Php::value overloads the constructor and operator = operator, common data types (integers, strings, floating point numbers, arrays, etc.) can be returned directly.

//获取1-100的和
Php::Value mm_sum_1_100()
{
    int sum = 0;
    int i;
    for(i=1;i<=100;i++){
        sum += i;
    }
    return sum; //可以直接返回sum值,自动生成 Php::value 类型
}
Copy after login

PHP test code:

<?php
$sum = mm_sum_1_100();
echo &#39;sum (1~100) = &#39; . $sum . PHP_EOL;
?>
Copy after login

Run the above PHP code, the output result is

sum (1~100) = 5050
Copy after login

3. How to write the extension function with parameters and no return value

Function function: calculate any given integer and print all prime numbers within the integer

Function name: mm_print_pn_any

Register function mm_print_pn_any, the registration method is the same as the previous section

extension.add<mm_print_pn_any>("mm_print_pn_any");
Copy after login

The function declaration and code are as follows. Since parameters are required, the function parameters need to be written as Php::Parameters ¶ms. Since there is no return value, the return value type is set to void.
In addition, it is necessary to check whether the parameters are input, and the type of the parameters also needs to be checked whether it is an integer. If used directly without detection, the code is prone to exceptions.

//任意给定一个整数,打印出小于等于该整数的所有素数
void mm_print_pn_any(Php::Parameters &params)
{
    //检查必须输入一个参数
    if(params.size() == 0){
        Php::out << "error: need a parameter " << std::endl;
        return;
    }
    //检查参数必须是整形
    if( params[0].type() != Php::Type::Numeric){
        Php::out << "error: parameter must be numeric" << std::endl;
        return;
    }
    //检查数字必须大于1
    int number = params[0];
    if(number <= 1){
        Php::out << "error: parameter must be larger than 1" << std::endl;
        return;
    }
    //检查参数必须大于0
    int x = 2;
    int y = 1;
    int line = 0;
    while (x <= number){
        int z = x - y; //z随y递减1
        int a = x%z; //取余数
        if (a == 0) { //如果x被z整除
            if (z == 1) {//如果z为1(x是质数)
                Php::out << x << " ";//输出x
                line ++;//每行输出的数的数量加1
             }
            x ++; //x加1
            y = 1;//y还原
        }
        else {//如果没有被整除
            y ++;//y加1,下一次循环中z减1
        }
        if (line == 10) {//每输出10个数
            Php::out << std::endl;//输出一个换行        
            line = 0;//还原line
        }
    }
    if (line != 0) //最后一行输出换行
        Php::out << std::endl;
    Php::out.flush();    
}
Copy after login

PHP test code

<?php
echo &#39;---runing mm_print_pn_any()---&#39; . PHP_EOL;
mm_print_pn_any();

echo PHP_EOL . &#39;---runing mm_print_pn_any(\&#39;xyz\&#39;)---&#39; . PHP_EOL;
mm_print_pn_any(&#39;xyz&#39;);

echo PHP_EOL . &#39;---runing mm_print_pn_any(200)---&#39; . PHP_EOL;
mm_print_pn_any(200);
?>
Copy after login

Run the above PHP code, the output result is

---runing mm_print_pn_any()---
error: need a parameter

---runing mm_print_pn_any(&#39;xyz&#39;)---
error: parameter must be numeric

---runing mm_print_pn_any(200)---
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199
Copy after login

4. Scalar parameters, extension function writing with return value

Function function: Given a series of parameters, calculate the sum

Function name: mm_sum_all

Register the extension function mm_sum_all, the registration method is the same as the previous section

extension.add<mm_sum_all>("mm_sum_all");
Copy after login

Function declaration and code as follows.

//获取所有参数的和
Php::Value mm_sum_all(Php::Parameters &params)
{
    int sum = 0;
    for (auto &param : params){
        //字符串类型可以自动转换成整形
        sum += param;
    }
    return sum;
}
Copy after login

PHP test code

<?php

$sum = mm_sum_all(1,2,&#39;3&#39;,&#39;5&#39;); //字符串类型可以自动转换成整形
echo &#39;sum (1,2,\&#39;3\&#39;,\&#39;5\&#39;) = &#39; . $sum . PHP_EOL;
?>
Copy after login

Test output result:

sum (1,2,&#39;3&#39;,&#39;5&#39;) = 11
Copy after login

5. Array parameters, extension function writing method with return value

Function function: Given a parameter of array type, calculate the sum of all elements of the array

Function name: mm_sum_array

Register function mm_sum_array, the registration method is the same as the first section

Function declaration and code as follows.

//获取所有数组各元素的和
Php::Value mm_sum_array(Php::Parameters &params)
{
    //没有给定参数,返回0
    if(params.size() == 0){
        return 0;
    }
    //参数类型不是数组,转成整形返回
    if( params[0].type() != Php::Type::Array){
        return (int)params[0];
    }
    //数组中的元素逐个相加
    int sum = 0;
    Php::Value array = params[0];
    int size = array.size();
    int i;
    for(i=0;i<size;i++){
        sum += array.get(i);
    }
    return sum;
}
Copy after login

PHP test code

<?php
$nums = array(1,3,5,7);
$sum = mm_sum_array($nums);
echo &#39;sum (array(1,3,5,7)) = &#39; . $sum . PHP_EOL;
?>
Copy after login

Test output result:

sum (array(1,3,5,7)) = 16
Copy after login

6. The return value type is an array extension function writing method

The return value of the above function They are all scalar types. Arrays are a particularly commonly used type in PHP. If you want to return an array type, you can use c's std::vector. PHP-CPP will thoughtfully convert it into an array type recognized by PHP.

The function of our current demonstration function is to "return an array of all prime numbers within 30". The method of registering functions in the extension is the same as in the first section.

The function declaration and code are as follows.

//获取30以内的所有素数
Php::Value mm_get_pn_30()
{
    std::vector<int> pn;
    int x = 2;
    int y = 1;
    while (x <= 30){
        int z = x - y; //z随y递减1
        int a = x%z; //取余数
        if (a == 0) { //如果x被z整除
            if (z == 1) {//如果z为1(x是质数)
                pn.push_back(x); //放数组中去
            }
            x ++; //x加1
            y = 1;//y还原
        }
        else {//如果没有被整除
            y ++;//y加1,下一次循环中z减1
        }
    }    
    return pn;
}
Copy after login

PHP test code

<?php
$pn = mm_get_pn_30();
var_dump($pn);
?>
Copy after login

Test output result:

array(10) {
  [0]=>
  int(2)
  [1]=>
  int(3)
  [2]=>
  int(5)
  [3]=>
  int(7)
  [4]=>
  int(11)
  [5]=>
  int(13)
  [6]=>
  int(17)
  [7]=>
  int(19)
  [8]=>
  int(23)
  [9]=>
  int(29)
}
Copy after login

7. References

c Prime number determination and output prime number table
PHP- CPP function development help

Related recommendations:

Comparison and introduction of related development technologies for PHP extension development

The writing of PHP extension development An extension hello world


#

The above is the detailed content of PHP extension development: developing our own mathematical function library. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template