Table of Contents
What are the benefits of using C to develop PHP extensions?
How to start using C for PHP extension development?
What is PHP-CPP and how does it help PHP extension development?
Can I use PHP-CPP for commercial projects?
What are some common challenges for PHP extension development using C and how can I overcome them?
How to debug PHP extensions written in C?
Can I use PHP-CPP with other C libraries?
How to improve the performance of PHP extensions written in C?
Can I contribute code to the PHP-CPP project?
Where can I find more resources on using C for PHP extension development?
Home Backend Development PHP Tutorial Developing PHP Extensions with C and PHP-CPP: Advanced

Developing PHP Extensions with C and PHP-CPP: Advanced

Feb 18, 2025 pm 12:30 PM

Develop PHP extensions with C and PHP-CPP: Advanced Topics and Best Practices

Key Points

  • Developing PHP extensions with C and PHP-CPP involves advanced topics such as returning "this" pointers, returning complex object pointers, exposing magic methods, linking member function calls, and exception throwing and handling in PHP. __toString
  • PHP-CPP library is ideal for projects that require software, data structures or algorithms for non-PHP projects in the future, or projects that require using tools or libraries not yet provided as PHP extensions. It also provides the performance advantages of C/C code while maintaining structured, object-oriented code for easy understanding and maintenance.
  • PHP-CPP library can be used for personal and commercial projects. However, while the library itself is free, it may take time and resources to learn how to use it effectively and maintain PHP extensions.
  • Common challenges in PHP extension development using C include the correct management of memory, handling of errors and exceptions, and the interface between PHP and C. These challenges can be overcome by gaining insight into PHP and C, using good programming practices, and leveraging the features and tools provided by PHP-CPP.
In my previous post, I introduced the PHP-CPP library that uses C (first and second posts) to create PHP extensions. In the latter post, I demonstrate the object-oriented aspect of writing PHP extensions using Complex class for plural operations.

Developing PHP Extensions with C   and PHP-CPP: Advanced

This introduction is not complete, because the main focus of the article is more on demonstrating the object-oriented capabilities of PHP-CPP than on the details of the object-oriented implementation.

In this article, we will further dive into the development of the Complex library, add more member functions, and address some advanced topics in writing object-oriented PHP extensions using PHP-CPP:

    Return this pointer;
  • Returns the Complex object pointer, i.e. Complex *;
  • Open
  • Magic method; __toString
  • Chain member function call;
  • Top the exception and handle it in PHP
The complete Complex library source code and test PHP scripts are located in this Github repository.

Let's get started.

Preparation

The entire process of preparing the environment is explained in the first article.

Return this pointer in C

As mentioned in the second article, we use member functions to perform various mathematical operations on complex numbers. In this demonstration, we will implement four such functions: add, sub, mul, and div. I will explain the first three first. The div function involves exception handling, which will be discussed later.

Let's take a look at the mul function (for multiplication). The add and sub functions are roughly the same.

Php::Value add(Php::Parameters &params) {
    Php::Value t = params[0];
    Complex *a = (Complex *) t.implementation();

    r += (double) a->getReal();
    i += (double) a->getImage();

    return this;
}
Copy after login
Copy after login
Copy after login
Note: In this article, I will not introduce some basic topics discussed before, such as modifying Makefile and ini files, registering member functions, classes and namespaces, etc. Please refer to the previous section for these contents.

Returning this pointer from C to PHP is simple. Inside this C function, this pointer (as Complex* type) can be returned to PHP as Php::Value type. The conversion does not lose any object information. It also does not require explicit type conversion.

Return Complex object pointer

Returning this usually means that the object itself has changed. But in some cases we might want to return a new object and leave the "current" object (call object) unchanged.

In our Complex class, we have a function like this that returns the conjugate number of a given complex number (a bi becomes a-bi).

Php::Value add(Php::Parameters &params) {
    Php::Value t = params[0];
    Complex *a = (Complex *) t.implementation();

    r += (double) a->getReal();
    i += (double) a->getImage();

    return this;
}
Copy after login
Copy after login
Copy after login

The key point here is that we have to use Php::Object to explicitly convert our Complex* object to Php::Object, so when the object is later parsed by the PHP script, the class information is properly ensured and kept Its accessibility.

The first parameter of this function is the class type, in this case trComplex. I'm using this name because I've wrapped this class ("Complex") into a separate namespace ("tr").

The second parameter is the object to be passed back.

Returning a new class instance is a bit trickier than just returning this pointer, but it is still manageable as long as you read the documentation and find the correct part. For more usage examples, you may want to read this section in the official PHP-CPP documentation.

Open __toString magic method

In our class, there is a __toString function that prints plural numbers in a more readable way, for example: 1 2i. In my previous post, this function is not exposed (or "registered" in PHP-CPP terminology), but it can still be called from inside PHP. However, in order for this function to be called on the Complex object after we apply some mathematical operations (e.g. "echo $a->add($b)->sub($c)"), we need to be compiled It is explicitly registered in the extension:

Php::Value conjugate() {
    Complex *t = new Complex();

    t->r = r;
    t->i = -i;

    return Php::Object("tr\Complex", t);
}
Copy after login
Copy after login

The issue we submitted in the PHP-CPP repository Issue #150 discusses in detail why we have to do this.

Chain member function call

One thing that must be implemented in this class is to be able to link member functions so that we can do the following calculation: $a->add($b)->sub($c). The result should still be able to call its member functions.

This is done by the above method, that is, returning this pointer to PHP. However, older PHP-CPP libraries have errors when dereferenced objects, and if the link method is called, a "segment fault" is created.

The issue was submitted (#151) and a commit containing the PHP-CPP source code patch was submitted. If you are using an older version of the PHP-CPP library to compile the PHP-CPP library and your own library, please update the PHP source code and recompile and reinstall the PHP-CPP library and your library.

As explained in the submission summary:

complex.method("__toString", &Complex::__toString);
Copy after login
Copy after login

I'm glad my own project work can help the libraries I use become better.

Exception throwing and handling in PHP

Two more functions in our Complex class may throw exceptions back to PHP for processing: div and phi. The former performs division operation, while the latter returns the angle of the complex number, as shown in its alternative representation, polar coordinate representation (r, θ).

If you pass a plural number as a parameter (or caller), but the part and imaginary parts are actually 0, both operations may fail. For these two operations, we need to perform exception handling. Remember that we are throwing exceptions in C code, and the PHP script will catch the exception and do the necessary processing:

Php::Value add(Php::Parameters &params) {
    Php::Value t = params[0];
    Complex *a = (Complex *) t.implementation();

    r += (double) a->getReal();
    i += (double) a->getImage();

    return this;
}
Copy after login
Copy after login
Copy after login

In PHP scripts, we catch this exception like this:

Php::Value conjugate() {
    Complex *t = new Complex();

    t->r = r;
    t->i = -i;

    return Php::Object("tr\Complex", t);
}
Copy after login
Copy after login

The above code snippet will display the following text line:

complex.method("__toString", &Complex::__toString);
Copy after login
Copy after login

It's very simple, right? The C exception constructed in our extension is passed back to PHP and is correctly caught. In addition, we can operate exceptions like we handle native PHP exceptions thrown by other PHP codes!

Test all functions

Finally, we can compile and install the complex.so extension for our PHP installation via make && sudo make install. If all goes well, we can verify the installation of the extension by issuing the following command in the terminal:

<code>修复问题#151,链式方法调用无法正常工作……
……因为每个对象的引用计数未正确更新,这导致即使对象已分配给不同的变量,该对象也会被销毁。</code>
Copy after login

The terminal should display a line that says "/etc/php5/cli/conf.d/complex.ini", we can make sure that our extension is installed and ready to be called by any PHP script.

Note: If we check the Makefile for this extension, we will see that we are installing this PHP extension into its CLI environment. If we want to install this extension so that Apache can load it, we change the following line:

Php::Value div(Php::Parameters &params) {
    Php::Value t = params[0];
    Complex *b = (Complex*) t.implementation();

    double t1 = b->mod() * b->mod();

    if (t1 == 0)
        throw Php::Exception("Division by zero");

    double tr = r * (double) (b->getReal()) + i * (double) (b->getImage());
    double ti = i * (double) (b->getReal()) - r * (double) (b->getImage());

    r = tr / t1;
    i = ti / t1;

    return this;
}
Copy after login

The test PHP script for this extension is as follows, with some notes:

$a=new tr\Complex(1,2);
$c=new tr\Complex(); //$c实际上是0+0i

try
{
    $res=$a->div($c);
}
catch(Exception $e)
{
    echo "Caught exception: ".$e->getMessage()."\n";
}
}
Copy after login

All test scripts should run correctly and the exception is caught correctly.

Conclusion

This summarizes my 3 article series on building this powerful library with C for PHP extensions. We cover the basics, object-oriented aspects, and some advanced topics in object-oriented programming. We also helped PHP-CPP improve.

What else can we do with PHP-CPP? I'll quote a few lines of email communication I received from Emiel Bruijntjes (co-author of PHP-CPP):

If you are working on a project and have one or more of the following requirements, the PHP-CPP library is ideal: – You are working on software/data structures/algorithms and you want to make sure that your software can also be used in non-PHP projects in the future. – You want to use a tool or library that is not yet available as a PHP extension. – You want better performance of your C/C code (compared to PHP), but you also want to build structured, object-oriented code for easy understanding and maintenance by other developers/colleagues.

The possibilities are huge: frameworks (such as Phalcon), template languages ​​(such as Smarty or Twig), and so on.

Please leave your comments and opinions and let us know what you have done with this library!

FAQs on Developing PHP Extensions with C

What are the benefits of using C to develop PHP extensions?

There are many benefits to developing PHP extensions using C. First, it allows you to take advantage of the power and flexibility of C in your PHP application. This can improve performance, especially in compute-intensive tasks. Second, it provides a way to reuse existing C code in a PHP environment, which can save a lot of development time and effort. Finally, it enables you to create custom PHP extensions that extend the functionality of PHP and provide features that are not available in the standard PHP library.

How to start using C for PHP extension development?

To start using C for PHP extension development, you need to have a basic understanding of PHP and C programming languages. You also need to install the PHP development environment and the C compiler. After installing these prerequisites, you can start writing PHP extensions in C. There are a lot of resources available online, including tutorials and sample code to guide you through this process.

What is PHP-CPP and how does it help PHP extension development?

PHP-CPP is a library for developing PHP extensions using C. It provides a set of C classes and methods, simplifying the process of writing PHP extensions. With PHP-CPP, you can write PHP extensions in a more natural and intuitive way, using C's familiar syntax and concepts. This can make the development process more efficient and reduce errors.

Can I use PHP-CPP for commercial projects?

Yes, PHP-CPP is open source software that can be used in personal and commercial projects. However, it is important to understand that while the library itself is free, you may need to invest time and resources in learning how to use it effectively and maintain your PHP extensions.

What are some common challenges for PHP extension development using C and how can I overcome them?

Some common challenges in PHP extension development using C include the correct management of memory, handling of errors and exceptions, and the interface between PHP and C. These challenges can be overcome by gaining insight into PHP and C, using good programming practices, and leveraging the features and tools provided by PHP-CPP.

How to debug PHP extensions written in C?

PHP extensions written in C can be debugged using standard C debugging tools. In addition, PHP-CPP provides some features that can aid debugging, such as exception handling and error reporting.

Can I use PHP-CPP with other C libraries?

Yes, PHP-CPP can be used with other C libraries. This allows you to take advantage of various C features in PHP extensions.

How to improve the performance of PHP extensions written in C?

You can improve the performance of PHP extensions by using efficient algorithms and data structures, minimizing memory usage, and optimizing C code. In addition, PHP-CPP provides some features that can help improve performance, such as direct access to PHP variables and functions.

Can I contribute code to the PHP-CPP project?

Yes, the PHP-CPP project is open source and the contribution of the community is welcome. You can contribute your code by reporting bugs, suggesting new features, or submitting patches.

Where can I find more resources on using C for PHP extension development?

There are many resources available online for learning to use C for PHP extension development. These resources include tutorials, sample code, documentation, and forums. In addition, the PHP-CPP website provides a large amount of information and resources on the use of the library.

The above is the detailed content of Developing PHP Extensions with C and PHP-CPP: Advanced. 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)

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

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 is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

See all articles