summaryrefslogtreecommitdiff
path: root/Examples/CppClassesInPhp/cppclassinphp.cpp
blob: 3164866479a6aa33b0a84c268a25a03a1ffc40f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
 *  cppclassinphp.cpp
 *  @author Jasper van Eck<jasper.vaneck@copernica.com>
 * 
 *  An example file to show the working of using a C++ class in PHP.
 */

#include "includeMyCustomClass.h"
/**
 *  Namespace to use
 */
using namespace std;

class MyCustomClass : public Php::Base
{
private:
    int _x;
    
public:
    MyCustomClass()
    {
        _x = 3;
        std::cout << "MyCustomClass::MyCustomClass" << std::endl;
        std::cout << _x << std::endl;
    }
    
    virtual ~MyCustomClass()
    {
        std::cout << "MyCustomClass::~MyCustomClass" << std::endl;
    }

    virtual void __construct()
    {
        std::cout << "MyCustomClass::__construct" << std::endl;
    }

    virtual void __destruct()
    {
        std::cout << "MyCustomClass::__destruct" << std::endl;
    }
    
    void myMethod(Php::Parameters &params)
    {
        std::cout << "myMethod is called." << std::endl;
        std::cout << "_x: " << _x << std::endl;
        _x = params[0];
        std::cout << "New _x" << _x << std::endl;
    }
};

void myFunction(Php::Parameters &params)
{
    std::cout << "regular function" << std::endl;
}


// Symbols are exported according to the "C" language
extern "C" 
{
    // export the "get_module" function that will be called by the Zend engine
    PHPCPP_EXPORT void *get_module()
    {
        // create extension
        static Php::Extension extension("Cpp_classes_in_php","1.0");
        
        // add custom function
        extension.add("myFunction", myFunction, { });
        
        // we are going to define a class
        Php::Class<MyCustomClass> customClass("MyClass");
        
        // add methods to it
        customClass.add("myMethod", &MyCustomClass::myMethod, Php::Final, {});
        customClass.add("property1", "bla");
        customClass.add("property2", "bla", Php::Protected);
        
        // add the class to the extension
        extension.add(customClass);
                
        // return the extension module
        return extension.module();
    }
}