Table of Contents
1. Without parameters, How to write an extension function without a return value
2. How to write the extension function without parameters and return value
3. How to write the extension function with parameters and no return value
4. Scalar parameters, extension function writing with return value
5. Array parameters, extension function writing method with return value
6. The return value type is an array extension function writing method
7. References
Home Backend Development PHP Tutorial PHP extension development: developing our own mathematical function library

PHP extension development: developing our own mathematical function library

Apr 13, 2018 pm 04:20 PM
php us

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!

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

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.

See all articles