Home >Backend Development >PHP Tutorial >PHP Extension Development with PHP-CPP: Object Oriented Code

PHP Extension Development with PHP-CPP: Object Oriented Code

Christopher Nolan
Christopher NolanOriginal
2025-02-21 09:17:13153browse

PHP Extension Development with PHP-CPP: Object Oriented Code

This article continues the exploration of building PHP extensions using PHP-CPP, focusing on object-oriented features. We'll create a Complex number class to illustrate the library's capabilities.

To begin, we'll adapt the PHP-CPP project template. Rename yourtextension.ini to complex.ini and update its content to extension=complex.so. Modify the Makefile as follows:

<code class="language-makefile">NAME                =   complex
INI_DIR             =   /etc/php5/cli/conf.d</code>

Next, we'll define the Complex class in main.cpp.

Key Concepts:

  • PHP-CPP simplifies object-oriented PHP extension development using familiar C syntax.
  • The Complex class showcases C and PHP-style constructors/destructors for seamless integration.
  • Methods like mod() and add() demonstrate method registration, allowing PHP scripts to directly use C class functionality.
  • PHP "magic methods" (e.g., __toString()) enhance interaction with objects in PHP scripts.
  • The article provides a complete guide to configuring, compiling, and testing PHP extensions.

C and PHP Constructors/Destructors:

C uses constructors (functions with the class name, no return type) and destructors (class name prefixed with ~, no return type, no parameters). PHP uses __construct() and __destruct(). PHP-CPP supports both:

<code class="language-cpp">class Complex : public Php::Base {
private:
    double r = 0, i = 0;

public:
    Complex() {}
    virtual ~Complex() {}

    Php::Value getReal() { return r; }
    Php::Value getImage() { return i; }

    void __construct(Php::Parameters &params) {
        if (params.size() == 2) {
            r = params[0];
            i = params[1];
        } else {
            r = 0;
            i = 0;
        }
    }
    // ... other methods ...
};</code>

Important points:

  1. All classes must inherit from Php::Base.
  2. Both C and PHP-style constructors are implemented.
  3. getReal() and getImage() provide access to private members.
  4. The PHP constructor handles initialization.

mod() Method:

This method calculates the modulus of a complex number:

<code class="language-cpp">Php::Value mod() const {
    return (double)sqrt(r * r + i * i);
}</code>

Remember to include <cmath></cmath> for sqrt(). PHP-CPP supports specific member function signatures (see the article for details).

add() Method:

Adding two complex numbers:

<code class="language-cpp">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;
}</code>

t.implementation() is crucial for casting a Php::Value to its underlying C object.

__toString() Method:

For user-friendly output:

<code class="language-cpp">Php::Value __toString() {
    std::ostringstream os;
    os << r;
    if (i >= 0) os << "+";
    os << i << "i";
    return os.str();
}</code>

Include <sstream></sstream> for string manipulation.

Function Registration:

Registering the class and its methods:

<code class="language-cpp">extern "C" {
    PHPCPP_EXPORT void *get_module() {
        static Php::Extension myExtension("complex", "1.0");
        Php::Class<complex> complex("Complex");
        complex.method("mod", &Complex::mod, {});
        complex.method("__construct", &Complex::__construct);
        complex.method("add", &Complex::add, {Php::ByVal("op", "Complex", false, true)});
        myExtension.add(std::move(complex));
        return myExtension;
    }
}</complex></code>

Compilation, Installation, and Testing:

Compile and install using make && sudo make install. Test with PHP code (see the original article for examples).

Namespace Encapsulation:

Wrapping the class in a namespace (trComplex in this example) requires minimal changes (see the original article for details). The key is adjusting the namespace in the get_module() function and using the fully qualified name in PHP code.

Conclusion:

PHP-CPP offers a streamlined approach to creating PHP extensions. While documentation improvements are suggested, its ease of use and features make it a valuable tool. The article provides a comprehensive guide, covering essential aspects of object-oriented PHP extension development.

The above is the detailed content of PHP Extension Development with PHP-CPP: Object Oriented Code. 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