summaryrefslogtreecommitdiff
path: root/documentation/magic-methods.html
blob: 6356d2a7b82a5a12b3aefae1a8f72a64f7b187b2 (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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
<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. Using some
    C++ compiler tricks, the C++ compiler detects whether the methods exist
    in your class, and if they do, they will be compiled into your extension
    and called when they are accessed from PHP.
</p>
<h2 id="compile-time-detection">Compile time detection</h2>
<p>
    Although you may have expected that the magic methods are virtual methods in
    the Php::Base class that can be overridden, they are not. The methods are
    detected by the C++ compiler at compile time - and are very normal methods
    that just happen to have a certain name.
</p>
<p>
    Because of the compile time detection, the signature of the methods is 
    somewhat flexible. The return values of many magic methods are assigned to 
    Php::Value objects, which means that as long as you make sure
    that your magic method returns a type that is assignable to a Php::Value,
    you can use it in your class. Your __toString() method may thus return a
    char*, a std::string, Php::Value (and even an integer!), because all these
    types can be assigned to a Php::Value.
</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 id="constructors">Constructors</h2>
<p>
    Normally, magic methods do not have 
    to be registered to make them work. When you add a magic method like 
    __toString() or __get() to your class, it will automatically be 
    called when an object is casted to a string or a property is accessed. There
    is no need to enable the magic method explicitly in the get_module() startup
    function.
</p>
<p>
    The only exception to this rule is the __construct() method. This method 
    does have to be explicitly registered. There are a number of reasons for this.
    For a start, the __construct() method does not have a fixed signature, and
    by explicitly adding it to the extension, you can also specify what
    parameters it accepts, and whether the __construct() method should be public,
    private or protected (if you want to create classes that can not be 
    instantiated from PHP).
</p>
<p>
    The other reason why you have to explicitly register the __construct() method,
    is that, unlike other magic methods, the __construct method <i>must</i> 
    be visible from PHP. Inside constructors of derived classes, it often is 
    necessary to make a call to parent::__construct(). By registering the 
    __construct() method in the get_module() function you make the function
    visible from PHP.
</p>
<p>
    We have a special article about <a href="constructors-and-destructors">
    constructors and destructors</a> with multiple examples how to register 
    the __construct() method.
<p>
<h2 id="clone-and-destruct">Clone and destruct</h2>
<p>
    The magic __clone() method is very similar to the __construct() method. It
    also is a method that is called directly <i>after</i> an object is constructed.
    The difference is that __clone() is called after an object is <i>copy 
    constructed</i> (or <i>cloned</i/> if you prefer the PHP idiom), while 
    __construct() is called right after the normal constructor.
</p>
<p>
    The magic __destruct() method gets called right before the object gets 
    destructed (and right before the C++ destructor runs).
</p>
<p>
    The __clone() and __destruct() methods are regular magic methods (unlike 
    __construct()) and you therefore do not have to register them to make them 
    active. If you add one of these two methods to your class, you will not have
    to make any changes to the get_module() startup function. The PHP-CPP library 
    calls them automatically if they are available.
</p>
<p>
    In normal circumstances you probably have no need for these methods.
    The C++ copy constructor and the C++ destructor can be used too. The only
    difference is that the magic methods are called on objects that are in a
    fully initialized state, while the C++ copy constructor and C++ destructor
    work on objects that are <i>being initialized</i>, or that are 
    <i>being destructed</i>.
</p>
<p>
    The article about mentioned above about <a href="constructors-and-destructors">
    constructors and destructors</a> has more details and examples.
</p>
<h2 id="pseudo-properties">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
     */
    Php::Value __get(const Php::Value &amp;name)
    {
        // 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
     */
    void __set(const Php::Value &amp;name, const Php::Value &amp;value) 
    {
        // 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
     */
    bool __isset(const Php::Value &amp;name) 
    {
        // 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
     */
    void __unset(const Php::Value &amp;name)
    {
        // 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 id="call-and-invoke">Magic methods __call(), __callStatic() 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>
    The __callStatic() method is similar to the __call() method, but works for
    static methods. A static call to YourClass::someMethod() can be automatically
    passed on to the __callStatic() method of your C++ class.
</p>
<p>
    Next to the magic __call() and __callStatic functions, 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>
<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
     */
    Php::Value __call(const char *name, Php::Parameters &amp;params)
    {
        // the return value
        std::string retval = std::string("__call ") + name;
        
        // loop through the parameters
        for (auto &amp;param : params)
        {
            // append parameter string value to return value
            retval += " " + param.stringValue();
        }
        
        // done
        return retval;
    }

    /**
     *  Overriden __callStatic() method to accept all static 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
     */
    static Php::Value __callStatic(const char *name, Php::Parameters &amp;params)
    {
        // the return value
        std::string retval = std::string("__callStatic ") + 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
     */
    Php::Value __invoke(Php::Parameters &amp;params)
    {
        // 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 some pseudo-methods in a static context
echo(MyClass::something()."\n");
echo(MyClass::myMethod(5,6,7)."\n");
echo(MyClass::whatever("x","y")."\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
__call something
__call myMethod 1 2 3 4
__call whatever a b
__callStatic something
__callStatic myMethod 5 6 7
__callStatic whatever x y
invoke parameter passed to invoke
</pre>
</p>
<h2 id="casting">Casting to a string</h2>
<p>
    In PHP you can add a __toString() method to a class. This method is automatically
    called when an object is casted to a string, or when an object is used in a string
    context. PHP-CPP supports this __toString() method too.
</p>
<p>
<pre class="language-c++"><code>
#include &lt;phpcpp.h&gt;

/**
 *  A sample class, with methods to cast objects to scalars
 */
class MyClass : public Php::Base
{
public:
    /**
     *  C++ constructor and C++ destructpr
     */
    MyClass() {}
    virtual ~MyClass() {}

    /**
     *  Cast to a string
     *  @return Value
     */
    Php::Value __toString()
    {
        return "abcd";
    }
};

/**
 *  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");
        
        // add the class to the extension
        myExtension.add(std::move(myClass));
        
        // return the extension
        return myExtension;
    }
}
</code></pre>
</p>
<p>
    Next to the magic methods described here, and that you probably already know 
    from writing PHP scripts, the PHP-CPP library also introduces a number of
    additional magic methods. These include extra casting methods, and a method
    to compare objects.
</p>
<p>
    You can read more about these additional features in the <a href="special-features">next section</a>.
</p>