search
HomeBackend DevelopmentPHP TutorialPHP extension development: developing our own mathematical function library

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

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;
}

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();
}

PHP test code

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

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

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");</mm_sum_1_100>

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 类型
}

PHP test code:

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

Run the above PHP code, the output result is

sum (1~100) = 5050

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");</mm_print_pn_any>

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();    
}

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

Run the above PHP code, the output result is

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

---runing mm_print_pn_any('xyz')---
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

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

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;
}

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;
?>

Test output result:

sum (1,2,'3','5') = 11

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;
}

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;
?>

Test output result:

sum (array(1,3,5,7)) = 16

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;
}

PHP test code

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

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

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!

Statement
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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP 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 GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP 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 LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP 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 BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.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?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP 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?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In 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 ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP 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.

See all articles

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool