summaryrefslogtreecommitdiff
path: root/documentation/magic-methods.html
blob: 17c6356544a7a1c65985b760171c8786fdb1c007 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
<h1>Magic methods</h1>
<p>
    Every PHP class has "magic methods". You may already know these methods
    from writing PHP code: the methods start with two underscores and have
    names like __set(), __isset(), __call(), etcetera.
</p>
<p>
    The PHP-CPP library also has support for these magic methods. The methods
    are already defined in the Php::Base class (which is the base class for
    all classes that are written using the PHP-CPP library), and can be 
    overridden in your derived class.
</p>
<p>
    The nice thing about magic methods implemented with PHP-CPP is that they
    do not become visible from PHP user space. In other words, when you define 
    a function like __set() or __unset() in your C++ class, these functions
    can not be called explicitly from PHP scripts - but they do get called
    when a property is accessed.
</p>
<h2>Pseudo properties</h2>
<p>
    With the methods __get(), __set(), __unset() and __isset() you can define 
    pseudo properties. It allows you to, for example, create read-only properties,
    or properties that are checked for validity when they are set.
<p>
<p>
    The magic methods work exactly the same as their counterparts in PHP scripts 
    do, so you can easily port PHP code that uses these properties to C++.
</p>
<p>
<pre class="language-c++"><code>
#include &lt;phpcpp.h&gt;

/**
 *  A sample class, that has some pseudo properties that map to native types
 */
class User : public Php::Base
{
private:
    /**
     *  Name of the user
     *  @var    std::string
     */
    std::string _name;
    
    /**
     *  Email address of the user
     *  @var    std::string
     */
    std::string _email;

public:
    /**
     *  C++ constructor and C++ destructpr
     */
    User() {}
    virtual ~User() {}

    /**
     *  Get access to a property
     *  @param  name        Name of the property
     *  @return Value       Property value
     */
    virtual Php::Value __get(const Php::Value &amp;name) override
    {
        // check if the property name is supported
        if (name == "name") return _name;
        if (name == "email") return _email;
        
        // property not supported, fall back on default
        return Php::Base::__get(name);
    }
    
    /**
     *  Overwrite a property
     *  @param  name        Name of the property
     *  @param  value       New property value
     */
    virtual void __set(const Php::Value &amp;name, const Php::Value &amp;value) override
    {
        // check the property name
        if (name == "name") 
        {
            // store member
            _name = value.stringValue();
        }
        
        // we check emails for validity
        else if (name == "email")
        {
            // store the email in a string
            std::string email = value;
            
            // must have a '@' character in it
            if (email.find('@') == std::string::npos) 
            {
                // email address is invalid, throw exception
                throw Php::Exception("Invalid email address");
            }
            
            // store the member
            _email = email;
        }
        
        // other properties fall back to default
        else
        {
            // call default
            Php::Base::__set(name, value);
        }
    }
    
    /**
     *  Check if a property is set
     *  @param  name        Name of the property
     *  @return bool
     */
    virtual bool __isset(const Php::Value &amp;name) override
    {
        // true for name and email address
        if (name == "name" || name == "email") return true;
        
        // fallback to default
        return Php::Base::__isset(name);
    }
    
    /**
     *  Remove a property
     *  @param  name        Name of the property to remove
     */
    virtual void __unset(const Php::Value &amp;name) override
    {
        // name and email can not be unset
        if (name == "name" || name == "email") 
        {
            // warn the user with an exception that this is impossible
            throw Php::Exception("Name and email address can not be removed");
        }
        
        // fallback to default
        Php::Base::__unset(name);
    }
};

/**
 *  Switch to C context to ensure that the get_module() function
 *  is callable by C programs (which the Zend engine is)
 */
extern "C" {
    /**
     *  Startup function that is called by the Zend engine 
     *  to retrieve all information about the extension
     *  @return void*
     */
    PHPCPP_EXPORT void *get_module() {
        
        // extension object
        static Php::Extension myExtension("my_extension", "1.0");
        
        // description of the class so that PHP knows 
        // which methods are accessible
        Php::Class&lt;User&gt; user("User");
        
        // add the class to the extension
        myExtension.add(std::move(user));
        
        // return the extension
        return myExtension;
    }
}
</code></pre>
</p>
<p>
    The above example shows how you can create a User class that seems to have a
    name and email property, but that does not allow you to assign an email
    address without a '@' character in it, and that does not allow you to
    remove the properties.
</p>
<p>
<pre code="language-php"><code>
&lt;?php
// initialize user and set its name and email address
$user = new User();
$user->name = "John Doe";
$user->email = "john.doe@example.com";

// show the email address
echo($user->email."\n");

// remove the email address (this will cause an exception)
unset($user->email);
?&gt;
</code></pre>
</p>
<h2>Magic methods __call() and __invoke()</h2>
<p>
    C++ methods need to be registered explicitly in your extension get_module() 
    startup function to be accessible from PHP user space. However, when you override the __call() 
    method, you can accept all calls - even calls to methods that do not exist. 
    When someone makes a call from user space to something that looks like a method, 
    it will be passed to this __call() method. In a script you can thus use
    $object->something(), $object->whatever() or $object->anything() - it does not 
    matter what the name of the method is, all these calls are passed on to the 
    __call() method in the C++ class.
</p>
<p>
    Next to the magic __call() function, the PHP-CPP library also supports the
    __invoke() method. This is a method that gets called when an object instance
    is used <i>as if</i> it was a function. This can be compared with overloading
    the operator () in a C++ class. By implementing the __invoke() method, scripts
    from PHP user space can create an object, and then use it as a function.
<p>
<pre class="language-c++"><code>
#include &lt;phpcpp.h&gt;

/**
 *  A sample class, that accepts all thinkable method calls
 */
class MyClass : public Php::Base
{
public:
    /**
     *  C++ constructor and C++ destructpr
     */
    MyClass() {}
    virtual ~MyClass() {}

    /**
     *  Regular method
     *  @param  params      Parameters that were passed to the method
     *  @return Value       The return value
     */
    Php::Value regular(Php::Parameters &amp;params)
    {
        return "this is a regular method";
    }

    /**
     *  Overriden __call() method to accept all method calls
     *  @param  name        Name of the method that is called
     *  @param  params      Parameters that were passed to the method
     *  @return Value       The return value
     */
    virtual Php::Value __call(const char *name, Php::Parameters &amp;params) override
    {
        // the return value
        std::string retval = name;
        
        // loop through the parameters
        for (auto &amp;param : params)
        {
            // append parameter string value to return value
            retval += " " + param.stringValue();
        }
        
        // done
        return retval;
    }

    /**
     *  Overridden __invoke() method so that objects can be called directly
     *  @param  params      Parameters that were passed to the method
     *  @return Value       The return value
     */
    virtual Php::Value __invoke(Php::Parameters &amp;params) override
    {
        // the return value
        std::string retval = "invoke";

        // loop through the parameters
        for (auto &amp;param : params)
        {
            // append parameter string value to return value
            retval += " " + param.stringValue();
        }
        
        // done
        return retval;
    }

};

/**
 *  Switch to C context to ensure that the get_module() function
 *  is callable by C programs (which the Zend engine is)
 */
extern "C" {
    /**
     *  Startup function that is called by the Zend engine 
     *  to retrieve all information about the extension
     *  @return void*
     */
    PHPCPP_EXPORT void *get_module() {
        
        // extension object
        static Php::Extension myExtension("my_extension", "1.0");
        
        // description of the class so that PHP knows 
        // which methods are accessible
        Php::Class&lt;MyClass&gt; myClass("MyClass");
        
        // register the regular method
        myClass.method("regular", &amp;MyClass::regular);
        
        // add the class to the extension
        myExtension.add(std::move(myClass));
        
        // return the extension
        return myExtension;
    }
}
</code></pre>
</p>
<p>
<pre code="language-php"><code>
&lt;?php
// initialize an object
$object = new MyClass();

// call a regular method
echo($object->regular()."\n");

// call some pseudo-methods
echo($object->something()."\n");
echo($object->myMethod(1,2,3,4)."\n");
echo($object->whatever("a","b")."\n");

// call the object as if it was a function
echo($object("parameter","passed","to","invoke")."\n");
?&gt;
</code></pre>
</p>
<p>
    The above PHP script calls some method on this class. And will generate
    the following output:
</p>
<p>
<pre>
regular
something
myMethod 1 2 3 4
whatever a b
invoke parameter passed to invoke
</pre>
</p>