import source from 1.3.40
[external/swig.git] / Doc / Manual / Php.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <!-- Hand crafted HTML -->
3 <html>
4 <head>
5 <title>SWIG and PHP</title>
6 <link rel="stylesheet" type="text/css" href="style.css">
7 </head>
8
9 <body bgcolor="#ffffff">
10 <H1><a name="Php"></a>29 SWIG and PHP</H1>
11 <!-- INDEX -->
12 <div class="sectiontoc">
13 <ul>
14 <li><a href="#Php_nn1">Generating PHP Extensions</a>
15 <ul>
16 <li><a href="#Php_nn1_1">Building a loadable extension</a>
17 <li><a href="#Php_nn1_3">Using PHP Extensions</a>
18 </ul>
19 <li><a href="#Php_nn2">Basic PHP interface</a>
20 <ul>
21 <li><a href="#Php_nn2_1">Constants</a>
22 <li><a href="#Php_nn2_2">Global Variables</a>
23 <li><a href="#Php_nn2_3">Functions</a>
24 <li><a href="#Php_nn2_4">Overloading</a>
25 <li><a href="#Php_nn2_5">Pointers and References</a>
26 <li><a href="#Php_nn2_6">Structures and C++ classes</a>
27 <ul>
28 <li><a href="#Php_nn2_6_1">Using <tt>-noproxy</tt></a>
29 <li><a href="#Php_nn2_6_2">Constructors and Destructors</a>
30 <li><a href="#Php_nn2_6_3">Static Member Variables</a>
31 <li><a href="#Php_nn2_6_4">Static Member Functions</a>
32 </ul>
33 <li><a href="#Php_nn2_7">PHP Pragmas, Startup and Shutdown code</a>
34 </ul>
35 <li><a href="#Php_nn3">Cross language polymorphism</a>
36 <ul>
37 <li><a href="#Php_nn3_1">Enabling directors</a>
38 <li><a href="#Php_nn3_2">Director classes</a>
39 <li><a href="#Php_nn3_3">Ownership and object destruction</a>
40 <li><a href="#Php_nn3_4">Exception unrolling</a>
41 <li><a href="#Php_nn3_5">Overhead and code bloat</a>
42 <li><a href="#Php_nn3_6">Typemaps</a>
43 <li><a href="#Php_nn3_7">Miscellaneous</a>
44 </ul>
45 </ul>
46 </div>
47 <!-- INDEX -->
48
49
50
51 <p>
52 SWIG supports generating wrappers for PHP5.  Support for PHP4 has been removed
53 as of SWIG 1.3.37.  The PHP developers are no longer making new PHP4 releases,
54 and won't even be patching critical security issues after 2008-08-08, so it
55 doesn't make much sense for SWIG to continue to support PHP4 at this point.
56 If you need to continue to use PHP4, stick with SWIG 1.3.36.
57 </p>
58
59 <p>
60 In this chapter, we discuss SWIG's support of PHP.  The PHP module
61 was extensively rewritten in release 1.3.26, and support for generating
62 OO wrappers for PHP5 was added in 1.3.30.  The PHP module works fairly
63 well, but currently does not implement all the
64 features available in some of the other languages.
65 </p>
66
67 <p>
68 In order to use this module, you will need to have a copy of the PHP5
69 include files to compile the SWIG generated files.  If you installed
70 PHP from a binary package, you may need to install a "php-dev" or "php-devel"
71 package for these to be installed.  You can find out where these files are
72 by running <tt>php-config --includes</tt>.  To use the built PHP module you
73 will need either the php binary or the Apache php module. If you want to build
74 your extension into php directly, you will need the complete PHP source tree
75 available.
76 </p>
77
78 <H2><a name="Php_nn1"></a>29.1 Generating PHP Extensions</H2>
79
80
81 <p>
82 To build a PHP extension, run swig using the <tt>-php</tt> option as
83 follows:
84 </p>
85
86 <div class="code"><pre>
87 swig -php example.i
88 </pre></div>
89
90 <p>
91 This will produce 3 files example_wrap.c, php_example.h and
92 example.php. The first file, <tt>example_wrap.c</tt> contains all of
93 the C code needed to build a PHP extension. The second file,
94 <tt>php_example.h</tt> contains the header information needed if
95 you wish to statically link the extension into the php interpreter.
96 The third file,
97 <tt>example.php</tt> can be included by PHP scripts.  It attempts to
98 dynamically load the extension and contains extra php code specified
99 in the interface file.  If wrapping C++ code with PHP classes, it will
100 also contain PHP5 class wrappers.
101 </p>
102
103 <p>
104 Swig can generate PHP extensions from C++ libraries as well when
105 given the <tt>-c++</tt> option.  The support for C++ is discussed in
106 more detail in <a href="#Php_nn2_6">section 27.2.6</a>.
107 </p>
108
109 <p>
110 The usual (and recommended) way is to build the extension as a separate
111 dynamically loaded module (which is supported by all modern operating
112 systems).  You can then specify that this be loaded
113 automatically in <tt>php.ini</tt> or load it explicitly for any script which
114 needs it.
115 </p>
116
117 <p>
118 It is also possible to rebuild PHP from source so that your module is
119 statically linked into the php executable/library.  This is a lot more
120 work, and also requires a full rebuild of PHP to update your module,
121 and it doesn't play nicely with package system.  We don't recommend
122 this approach, or provide explicit support for it.
123 </p>
124
125 <H3><a name="Php_nn1_1"></a>29.1.1 Building a loadable extension</H3>
126
127
128 <p>
129 To build your module as a dynamically loadable extension, use compilation
130 commands like these (if you aren't using GCC, the commands will be different,
131 and there may be some variation between platforms - these commands should at
132 least work for Linux though):
133 </p>
134
135 <div class="code"><pre>
136         gcc `php-config --includes` -fpic -c example_wrap.c
137         gcc -shared example_wrap.o -o example.so
138 </pre></div>
139
140 <H3><a name="Php_nn1_3"></a>29.1.2 Using PHP Extensions</H3>
141
142
143 <p>
144 To test the extension from a PHP script, you need to load it first. You
145 can load it for every script by adding this line the <tt>[PHP]</tt> section of
146 <tt>php.ini</tt>:
147 </p>
148
149 <div class="code"><pre>
150         extension=/path/to/modulename.so
151 </pre></div>
152
153 <p>
154 Alternatively, you can load it explicitly only for scripts which need it
155 by adding this line:
156 </p>
157
158 <div class="code"><pre>
159         dl("/path/to/modulename.so");   // Load the module
160 </pre></div>
161
162 <p>
163 to the start of each PHP file.  SWIG also generates a php module, which
164 attempts to do the <tt>dl()</tt> call for you:
165 </p>
166
167 <div class="code"><pre>
168         include("example.php");
169 </pre></div>
170
171 <H2><a name="Php_nn2"></a>29.2 Basic PHP interface</H2>
172
173
174 <p>
175 It is important to understand that PHP uses a single global namespace
176 into which all symbols from extension modules are loaded.  It is quite
177 possible for names of symbols in one extension module to clash with
178 other symbols unless care is taken to <tt>%rename</tt> them.
179 </p>
180
181 <H3><a name="Php_nn2_1"></a>29.2.1 Constants</H3>
182
183
184 <p>
185 These work in much the same way as in C/C++, constants can be defined
186 by using either the normal C pre-processor declarations, or the
187 <tt>%constant</tt> SWIG directive.  These will then be available from
188 your PHP script as a PHP constant, (i.e. no dollar sign is needed to
189 access them.) For example, with a swig interface file like this,
190 </p>
191
192 <div class="code"><pre>
193 %module example
194
195 #define PI 3.14159
196
197 %constant int E  = 2.71828
198 </pre>
199 </div>
200
201 <p>
202 you can access the constants in your php script like this,
203 </p>
204
205 <div class="code"><pre>
206 include("example.php");
207
208 echo "PI = " . PI . "\n";
209
210 echo "E = " . E . "\n";
211
212 </pre>
213 </div>
214
215 <p>
216 There are two peculiarities with using constants in PHP. The first is that
217 if you try to use an undeclared constant, it will evaluate to a string
218 set to the constant's name. For example,
219 </p>
220
221 <div class="code"><pre>
222 %module example
223
224 #define EASY_TO_MISPELL 0
225 </pre>
226 </div>
227
228 <p>
229 accessed incorrectly in PHP,
230 </p>
231
232 <div class="code">
233 <pre>
234 include("example.php");
235
236 if(EASY_TO_MISPEL) {
237         ....
238 } else {
239         ....
240 }
241
242 </pre>
243 </div>
244
245 <p>
246 will issue a warning about the undeclared constant, but will then
247 evaluate it and turn it into a string ('EASY_TO_MISPEL'), which
248 evaluates to true, rather than the value of the constant which would
249 be false. This is a feature!
250 </p>
251
252 <p>
253 The second 'feature' is that although constants are case sensitive (by
254 default), you cannot declare a constant twice with alternative
255 cases. E.g.,
256 </p>
257
258 <div class="code">
259 <pre>
260 %module example
261
262 #define TEST    Hello
263 #define Test    World
264 </pre>
265 </div>
266
267 <p>
268 accessed from PHP,
269 </p>
270
271 <div class="code">
272 <pre>
273 include("example.php");
274
275 echo TEST, Test;
276 </pre>
277 </div>
278
279 <p>
280 will output "Hello Test" rather than "Hello World". This is because
281 internally, all constants are stored in a hash table by their lower
282 case name, so 'TEST' and 'Test' will map to the same hash element
283 ('Test'). But, because we declared them case sensitive, the Zend
284 engine will test if the case matches with the case the constant was
285 declared with first.
286 </p>
287
288 <p>
289 So, in the example above, the TEST constant was declared first, and
290 will be stored under the hash element 'test'. The 'Test' constant will
291 also map to the same hash element 'test', but will not overwrite
292 it. When called from the script, the TEST constant will again be
293 mapped to the hash element 'test' so the constant will be
294 retrieved. The case will then be checked, and will match up, so the
295 value ('Hello') will be returned. When 'Test' is evaluated, it will
296 also map to the same hash element 'test'. The same constant will be
297 retrieved, this time though the case check will fail as 'Test' !=
298 'TEST'. So PHP will assume that Test is a undeclared constant, and as
299 explained above, will return it as a string set to the constant name
300 ('Test'). Hence the script above will print 'Hello Test'. If they were
301 declared non-case sensitive, the output would be 'Hello Hello', as
302 both point to the same value, without the case test taking place.  (
303 Apologies, this paragraph needs rewriting to make some sense. )
304 </p>
305
306 <H3><a name="Php_nn2_2"></a>29.2.2 Global Variables</H3>
307
308
309 <p>
310 Because PHP does not provide a mechanism to intercept access and
311 assignment of global variables, global variables are supported through
312 the use of automatically generated accessor functions.
313 </p>
314
315 <div class="code"><pre>
316 %module example;
317
318 %inline %{
319   double seki = 2;
320   void print_seki() {
321     zend_printf("seki is now %f\n",seki);
322   }
323 %}
324 </pre></div>
325
326 <p>
327 is accessed as follows:
328 </p>
329
330 <div class="code"><pre>
331 include("example.php");
332 print seki_get();
333 seki_set( seki_get() * 2);      # The C variable is now 4.
334 print seki_get();
335 </pre></div>
336
337 <p>
338 SWIG supports global variables of all C datatypes including pointers
339 and complex objects.  Additional types can be supported by using the
340 <tt>varinit</tt> typemap.
341 </p>
342
343 <p>
344 SWIG honors the <tt>%immutable</tt> modifier by not generating code
345 for the <tt>_set</tt> method.  This provides read-only access to the
346 variable from the php script.  Attempting to access the <tt>_set</tt>
347 method will result in a php fatal error because the function is
348 undefined.
349 </p>
350
351 <p>
352 At this time SWIG does not support custom accessor methods.
353 </p>
354
355 <H3><a name="Php_nn2_3"></a>29.2.3 Functions</H3>
356
357
358 <p>
359 C functions are converted into PHP functions. Default/optional arguments are
360 also allowed. An interface file like this :
361 </p>
362
363 <div class="code"><pre>
364 %module example
365 int foo(int a);
366 double bar(double, double b = 3.0);
367 ...
368 </pre></div>
369
370 <p>
371 Will be accessed in PHP like this :
372 </p>
373
374 <div class="code"><pre>
375 include("example.php");
376 $a = foo(2);
377 $b = bar(3.5, -1.5);
378 $c = bar(3.5);          # Use default argument for 2nd parameter
379
380 </pre></div>
381
382 <!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
383 <p>
384 Because PHP is a dynamically typed language, the default typemaps
385 used for simple types will attempt to coerce the arguments into the appropriate type.  That is the following invocations are equivalent:
386 </p>
387
388 <div class="code"><pre>
389 $a = foo(2);
390 $a = foo("2");
391 $a = foo(2.0);
392 </pre></div>
393
394 <p>
395 Functions are invoked using pass by value semantics like all of PHP.
396 This means the conversion which automatically takes place when
397 invoking a swig wrapped method does not change the native type of the
398 argument variable.
399 </p>
400 <div class="code"><pre>
401 $s = "2 A string representing two";
402 $a = foo($s);  # invokes 'foo(2)';
403 print $s;      # The value of $s was not changed.
404 </pre></div>
405 -->
406
407
408 <H3><a name="Php_nn2_4"></a>29.2.4 Overloading</H3>
409
410
411 <p>
412 Although PHP does not support overloading functions natively, swig
413 will generate dispatch functions which will use <tt>%typecheck</tt>
414 typemaps to allow overloading.  This dispatch function's operation and
415 precedence is described in <a
416 href="TypemapsSWIGPlus.html#SWIGPlus_overloaded_methods">Wrapping
417 Overloaded Functions and Methods</a>.
418 </p>
419
420 <!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
421 <p>
422 Because PHP is a dynamically typed language, simple values can be
423 silently converted from one type to another.  For example, integers,
424 doubles and strings silently convert to each other depending on
425 context.  This situation make overloading slightly problematic because
426 given the following function:
427 </p>
428
429 <div class="code"><pre>
430 void doit( int i );
431 void doit( double i );
432 </pre></div>
433
434 <p>
435 it is questionable which to invoke when <tt>doit("2");</tt> is used in
436 PHP.  The string <tt>"2"</tt> simultaneously represents the integer
437 <tt>2</tt> and the double <tt>2.0</tt>.
438 </p>
439
440 <p>
441 In order to provide the most natural experience to PHP programmers,
442 the default <tt>%typecheck</tt> implemented in <tt>php.swg</tt>
443 allows any simple type (integer, double, string) in PHP to be used for
444 any simple C type (int, double, char *).  The function selected then
445 depends only on the argument type precedence defined by SWIG.
446 </p>
447
448 <p>
449 It should be noted that <tt>SWIGTYPE</tt> references and pointers will
450 not be silently converted.  So these two functions:
451 </p>
452
453 <div class="code"><pre>
454 void doit( const Vector &amp; );
455 void doit( int i );
456 </pre></div>
457
458 <p>
459 Cause less confusion and <tt>doit("2");</tt> will invoke the function
460 taking the integer argument.
461 </p>
462 -->
463
464 <H3><a name="Php_nn2_5"></a>29.2.5 Pointers and References</H3>
465
466
467 <p>
468 Pointers to C/C++ objects are represented
469 as PHP resources, rather like MySQL connection handles.
470 </p>
471
472 <p>
473 There are multiple ways to wrap pointers to simple types.  Given the
474 following C method:
475 </p>
476
477 <div class="code"><pre>
478   void add( int *in1, int *in2, int *result);
479 </pre></div>
480
481 <p>
482 One can include <b>cpointer.i</b> to generate PHP wrappers to <tt>int
483 *</tt>.
484 </p>
485
486 <div class="code"><pre>
487 %module example
488 %include "cpointer.i"
489 %pointer_functions(int,intp)
490
491 void add( int *in1, int *in2, int *result);
492 </pre></div>
493
494 <p>
495 This will result in the following usage in PHP:
496 </p>
497
498 <div class="code"><pre>
499 &lt;?php
500
501 include("example.php");
502
503 $in1=copy_intp(3);
504 $in2=copy_intp(5);
505 $result=new_intp();
506
507 add( $in1, $in2, $result );
508
509 echo "The sum " . intp_value($in1) . " + " . intp_value($in2) . " = " . intp_value( $result) . "\n";
510 ?&gt;
511 </pre></div>
512
513 <p>
514 An alternative would be to use the include <b>typemaps.i</b> which
515 defines named typemaps for INPUT, OUTPUT and INOUT variables.  One
516 needs to either <tt>%apply</tt> the appropriate typemap or adjust the
517 parameter names as appropriate.
518 </p>
519
520 <div class="code"><pre>
521 %module example
522 %include "typemaps.i"
523
524 void add( int *INPUT, int *INPUT, int *OUTPUT);
525
526 </pre></div>
527
528 <p>
529 This will result in the following usage in PHP:
530 </p>
531
532 <div class="code"><pre>
533 &lt;?php
534
535 include("example.php");
536
537 $in1 = 3;
538 $in2 = 5;
539 $result= add($in1,$in2);  # Note using variables for the input is unnecessary.
540
541 echo "The sum $in1 + $in2 = $result\n";
542 ?&gt;
543 </pre></div>
544
545 <p>
546 Because PHP has a native concept of reference, it may seem more natural
547 to the PHP developer to use references to pass pointers.  To enable
548 this, one needs to include <b>phppointers.i</b> which defines the
549 named typemap REFERENCE.
550 </p>
551
552 <div class="code"><pre>
553 %module example
554 %include "phppointers.i"
555
556 void add( int *REF, int *REF, int *REF);
557
558 </pre></div>
559
560 <p>
561 This will result in the following usage in PHP:
562 </p>
563
564 <div class="code"><pre>
565 &lt;?php
566
567 include("example.php");
568
569 $in1 = 3;
570 $in2 = 5;
571 $result = 0;
572 add(&amp;$in1,&amp;$in2,&amp;$result);
573
574 echo "The sum $in1 + $in2 = $result\n";
575 ?&gt;
576 </pre></div>
577
578 <p>
579 It is important to note that a php variable which is NULL when passed
580 by reference would end up passing a NULL pointer into the function.
581 In PHP, an unassigned variable (i.e. where the first reference to the
582 variable is not an assignment) is
583 NULL.  In the above example, if any of the three variables had not
584 been assigned, a NULL pointer would have been passed into
585 <tt>add</tt>.  Depending on the implementation of the function, this
586 may or may not be a good thing.
587 </p>
588
589 <p>
590 We chose to allow passing NULL pointers into functions because that is
591 sometimes required in C libraries.  A NULL pointer can be created in
592 PHP in a number of ways: by using <tt>unset</tt> on an existing
593 variable, or assigning <tt>NULL</tt> to a variable.
594 </p>
595
596 <H3><a name="Php_nn2_6"></a>29.2.6 Structures and C++ classes</H3>
597
598
599 <p>
600 SWIG defaults to wrapping C++ structs and classes with PHP classes
601 unless "-noproxy" is specified.  For PHP5, a PHP wrapper
602 class is generated which calls a set of flat functions wrapping the C++ class.
603 </p>
604
605 <p>
606 This interface file
607 </p>
608
609 <div class="code"><pre>
610 %module vector
611
612 class Vector {
613 public:
614         double x,y,z;
615         Vector();
616         ~Vector();
617         double magnitude();
618 };
619
620 struct Complex {
621  double re, im;
622 };
623 </pre></div>
624
625 <p>
626 Would be used in the following way from PHP5:
627 </p>
628
629 <div class="code"><pre>
630 &lt;?php
631   require "vector.php";
632
633   $v = new Vector();
634   $v-&gt;x = 3;
635   $v-&gt;y = 4;
636   $v-&gt;z = 5;
637
638   echo "Magnitude of ($v-&gt;x,$v-&gt;y,$v-&gt;z) = " . $v-&gt;magnitude() . "\n";
639
640   $v = NULL;   # destructor called.
641
642   $c = new Complex();
643
644   $c-&gt;re = 0;
645   $c-&gt;im = 0;
646
647   # $c destructor called when $c goes out of scope.
648 ?&gt;
649 </pre></div>
650
651 <p>
652 Member variables and methods are accessed using the <tt>-&gt;</tt> operator.
653 </p>
654
655 <H4><a name="Php_nn2_6_1"></a>29.2.6.1 Using <tt>-noproxy</tt></H4>
656
657
658 <p>
659 The <tt>-noproxy</tt> option flattens the object structure and
660 generates collections of named functions (these are the functions
661 which the PHP5 class wrappers call).  The above example results
662 in the following PHP functions:
663 </p>
664
665 <div class="code"><pre>
666 new_Vector();
667 Vector_x_set($obj,$d);
668 Vector_x_get($obj);
669 Vector_y_set($obj,$d);
670 Vector_y_get($obj);
671 Vector_z_set($obj,$d);
672 Vector_z_get($obj);
673 Vector_magnitude($obj);
674 new_Complex();
675 Complex_re_set($obj,$d);
676 Complex_re_get($obj);
677 Complex_im_set($obj,$d);
678 Complex_im_get($obj);
679 </pre></div>
680
681 <H4><a name="Php_nn2_6_2"></a>29.2.6.2 Constructors and Destructors</H4>
682
683
684 <p>
685 The constructor is called when <tt>new Object()</tt> (or
686 <tt>new_Object()</tt> if using <tt>-noproxy</tt>) is used to create an
687 instance of the object. If multiple constructors are defined for an
688 object, function overloading will be used to determine which
689 constructor to execute.
690 </p>
691
692 <p>
693 Because PHP uses reference counting to manage resources, simple
694 assignment of one variable to another such as:
695 </p>
696
697 <div class="code"><pre>
698 $ref = $v;
699 </pre></div>
700
701 <p>
702 causes the symbol <tt>$ref</tt> to refer to the same underlying object
703 as <tt>$v</tt>.  This does not result in a call to the C++ copy
704 constructor or copy assignment operator.
705 </p>
706
707 <p>
708 One can force execution of the copy constructor by using:
709 </p>
710 <div class="code"><pre>
711 $o_copy = new Object($o);
712 </pre></div>
713
714 <p>
715 Destructors are automatically called when all variables referencing
716 the instance are reassigned or go out of scope.  The destructor is not
717 available to be called manually.  To force a destructor to be called
718 the programmer can either reassign the variable or call
719 <tt>unset($v)</tt>
720 </p>
721
722 <H4><a name="Php_nn2_6_3"></a>29.2.6.3 Static Member Variables</H4>
723
724
725 <p>
726 Static member variables in C++ are not wrapped as such in PHP
727 as it does not appear to be possible to intercept accesses to such variables.
728 Therefore, static member variables are
729 wrapped using a class function with the same name, which
730 returns the current value of the class variable. For example
731 </p>
732
733 <div class="code"><pre>
734 %module example
735
736 class Ko {
737         static int threats;
738 };
739
740 </pre></div>
741
742 <p>
743 would be accessed in PHP as,
744 </p>
745
746 <div class="code"><pre>
747 include("example.php");
748
749 echo "There has now been " . Ko::threats() . " threats\n";
750
751 </pre></div>
752
753 <p>
754 To set the static member variable, pass the value as the argument to the class
755 function, e.g.
756 </p>
757
758 <div class="code"><pre>
759
760 Ko::threats(10);
761
762 echo "There has now been " . Ko::threats() . " threats\n";
763
764 </pre></div>
765 <H4><a name="Php_nn2_6_4"></a>29.2.6.4 Static Member Functions</H4>
766
767
768 <p>
769 Static member functions are supported in PHP using the
770 <tt>class::function()</tt> syntax.  For example
771 </p>
772
773 <div class="code"><pre>
774 %module example
775 class Ko {
776   static void threats();
777 };
778 </pre></div>
779
780 would be executed in PHP as,
781 <div class="code"><pre>
782 include("example.php");
783 Ko::threats();
784 </pre></div>
785
786
787 <H3><a name="Php_nn2_7"></a>29.2.7 PHP Pragmas, Startup and Shutdown code</H3>
788
789
790 <p>
791 To place PHP code in the generated "example.php" file one can use the
792 <b>code</b> pragma. The code is inserted after loading the shared
793 object.
794 </p>
795
796 <div class="code"><pre>
797 %module example
798 %pragma(php) code="
799 # This code is inserted into example.php
800 echo \"example.php execution\\n\";
801 "
802 </pre></div>
803
804 <p>
805 Results in the following in "example.php"
806 </p>
807
808 <div class="code"><pre>
809 # This code is inserted into example.php
810 echo "example.php execution\n";
811 </pre></div>
812
813 <p>
814 The <b>include</b> pragma is a short cut to add include statements to
815 the example.php file.
816 </p>
817
818 <div class="code"><pre>
819 %module example
820 %pragma(php) code="
821 include \"include.php\";
822 "
823 %pragma(php) include="include.php"   // equivalent.
824 </pre></div>
825
826 <p>
827 The <b>phpinfo</b> pragma inserts code in the
828 <tt>PHP_MINFO_FUNCTION</tt> which is called from PHP's
829 phpinfo() function.
830 </p>
831
832 <div class="code"><pre>
833 %module example;
834 %pragma(php) phpinfo="
835   zend_printf("An example of PHP support through SWIG\n");
836   php_info_print_table_start();
837   php_info_print_table_header(2, \"Directive\", \"Value\");
838   php_info_print_table_row(2, \"Example support\", \"enabled\");
839   php_info_print_table_end();
840 "
841 </pre></div>
842
843 <p>
844 To insert code into the <tt>PHP_MINIT_FUNCTION</tt>, one can use
845 either <tt>%init</tt> or <tt>%minit</tt>.
846 </p>
847
848 <div class="code"><pre>
849 %module example;
850 %init {
851   zend_printf("Inserted into PHP_MINIT_FUNCTION\n");
852 }
853 %minit {
854   zend_printf("Inserted into PHP_MINIT_FUNCTION\n");
855 }
856 </pre></div>
857
858 <p>
859 To insert code into the <tt>PHP_MSHUTDOWN_FUNCTION</tt>, one can use
860 either <tt>%init</tt> or <tt>%minit</tt>.
861 </p>
862
863 <div class="code"><pre>
864 %module example;
865 %mshutdown {
866   zend_printf("Inserted into PHP_MSHUTDOWN_FUNCTION\n");
867 }
868 </pre></div>
869
870 <p>
871 The <tt>%rinit</tt> and <tt>%rshutdown</tt> statements insert code
872 into the request init and shutdown code respectively.
873 </p>
874
875 <H2><a name="Php_nn3"></a>29.3 Cross language polymorphism</H2>
876
877
878 <p>
879 Proxy classes provide a more natural, object-oriented way to access
880 extension classes. As described above, each proxy instance has an
881 associated C++ instance, and method calls to the proxy are passed to the
882 C++ instance transparently via C wrapper functions.
883 </p>
884
885 <p>
886 This arrangement is asymmetric in the sense that no corresponding
887 mechanism exists to pass method calls down the inheritance chain from
888 C++ to PHP. In particular, if a C++ class has been extended in PHP
889 (by extending the proxy class), these extensions will not be visible
890 from C++ code. Virtual method calls from C++ are thus not able access
891 the lowest implementation in the inheritance chain.
892 </p>
893
894 <p>
895 Changes have been made to SWIG 1.3.18 to address this problem and make
896 the relationship between C++ classes and proxy classes more symmetric.
897 To achieve this goal, new classes called directors are introduced at the
898 bottom of the C++ inheritance chain. Support for generating PHP classes
899 has been added in SWIG 1.3.40. The job of the directors is to route
900 method calls correctly, either to C++ implementations higher in the
901 inheritance chain or to PHP implementations lower in the inheritance
902 chain. The upshot is that C++ classes can be extended in PHP and from
903 C++ these extensions look exactly like native C++ classes. Neither C++
904 code nor PHP code needs to know where a particular method is
905 implemented: the combination of proxy classes, director classes, and C
906 wrapper functions takes care of all the cross-language method routing
907 transparently.
908 </p>
909
910 <H3><a name="Php_nn3_1"></a>29.3.1 Enabling directors</H3>
911
912
913 <p>
914 The director feature is disabled by default.  To use directors you
915 must make two changes to the interface file.  First, add the "directors"
916 option to the %module directive, like this:
917 </p>
918
919 <div class="code">
920 <pre>
921 %module(directors="1") modulename
922 </pre>
923 </div>
924
925 <p>
926 Without this option no director code will be generated.  Second, you
927 must use the %feature("director") directive to tell SWIG which classes 
928 and methods should get directors.  The %feature directive can be applied 
929 globally, to specific classes, and to specific methods, like this:
930 </p>
931
932 <div class="code">
933 <pre>
934 // generate directors for all classes that have virtual methods
935 %feature("director");         
936
937 // generate directors for all virtual methods in class Foo
938 %feature("director") Foo;      
939
940 // generate a director for just Foo::bar()
941 %feature("director") Foo::bar; 
942 </pre>
943 </div>
944
945 <p>
946 You can use the %feature("nodirector") directive to turn off
947 directors for specific classes or methods.  So for example,
948 </p>
949
950 <div class="code">
951 <pre>
952 %feature("director") Foo;
953 %feature("nodirector") Foo::bar;
954 </pre>
955 </div>
956
957 <p>
958 will generate directors for all virtual methods of class Foo except
959 bar().  
960 </p>
961
962 <p>
963 Directors can also be generated implicitly through inheritance. 
964 In the following, class Bar will get a director class that handles
965 the methods one() and two() (but not three()):
966 </p>
967
968 <div class="code">
969 <pre>
970 %feature("director") Foo;
971 class Foo {
972 public:
973     Foo(int foo);
974     virtual void one();
975     virtual void two();
976 };
977
978 class Bar: public Foo {
979 public:
980     virtual void three();
981 };
982 </pre>
983 </div>
984
985 <p>
986 then at the PHP side you can define
987 </p>
988
989 <div class="targetlang">
990 <pre>
991 require("mymodule.php");
992
993 class MyFoo extends Foo {
994   function one() {
995      print "one from php\n";
996   }
997 }
998 </pre>
999 </div>
1000
1001
1002 <H3><a name="Php_nn3_2"></a>29.3.2 Director classes</H3>
1003
1004
1005  
1006
1007
1008 <p>
1009 For each class that has directors enabled, SWIG generates a new class
1010 that derives from both the class in question and a special
1011 <tt>Swig::Director</tt> class. These new classes, referred to as director
1012 classes, can be loosely thought of as the C++ equivalent of the PHP
1013 proxy classes. The director classes store a pointer to their underlying
1014 PHP object.  Indeed, this is quite similar to the "_cPtr" and "thisown"
1015 members of the PHP proxy classes.
1016 </p>
1017
1018 <p>
1019 For simplicity let's ignore the <tt>Swig::Director</tt> class and refer to the
1020 original C++ class as the director's base class. By default, a director
1021 class extends all virtual methods in the inheritance chain of its base
1022 class (see the preceding section for how to modify this behavior).
1023 Thus all virtual method calls, whether they originate in C++ or in
1024 PHP via proxy classes, eventually end up in at the implementation in the
1025 director class. The job of the director methods is to route these method
1026 calls to the appropriate place in the inheritance chain. By "appropriate
1027 place" we mean the method that would have been called if the C++ base
1028 class and its extensions in PHP were seamlessly integrated. That
1029 seamless integration is exactly what the director classes provide,
1030 transparently skipping over all the messy extension API glue that binds
1031 the two languages together.
1032 </p>
1033
1034 <p>
1035 In reality, the "appropriate place" is one of only two possibilities:
1036 C++ or PHP. Once this decision is made, the rest is fairly easy. If the
1037 correct implementation is in C++, then the lowest implementation of the
1038 method in the C++ inheritance chain is called explicitly. If the correct
1039 implementation is in PHP, the Zend API is used to call the method of the
1040 underlying PHP object (after which the usual virtual method resolution
1041 in PHP automatically finds the right implementation).
1042 </p>
1043
1044 <p>
1045 Now how does the director decide which language should handle the method call?
1046 The basic rule is to handle the method in PHP, unless there's a good
1047 reason not to. The reason for this is simple: PHP has the most
1048 "extended" implementation of the method. This assertion is guaranteed,
1049 since at a minimum the PHP proxy class implements the method. If the
1050 method in question has been extended by a class derived from the proxy
1051 class, that extended implementation will execute exactly as it should.
1052 If not, the proxy class will route the method call into a C wrapper
1053 function, expecting that the method will be resolved in C++. The wrapper
1054 will call the virtual method of the C++ instance, and since the director
1055 extends this the call will end up right back in the director method. Now
1056 comes the "good reason not to" part. If the director method were to blindly
1057 call the PHP method again, it would get stuck in an infinite loop. We avoid this
1058 situation by adding special code to the C wrapper function that tells
1059 the director method to not do this.  The C wrapper function compares the
1060 called and the declaring class name of the given method.  If these are
1061 not the same, then the C wrapper function tells the director to resolve
1062 the method by calling up the C++ inheritance chain, preventing an
1063 infinite loop.
1064 </p>
1065
1066 <p>
1067 One more point needs to be made about the relationship between director
1068 classes and proxy classes. When a proxy class instance is created in
1069 PHP, SWIG creates an instance of the original C++ class and assigns it
1070 to <tt>-&gt;_cPtr</tt>. This is exactly what happens without directors
1071 and is true even if directors are enabled for the particular class in
1072 question. When a class <i>derived</i> from a proxy class is created,
1073 however, SWIG then creates an instance of the corresponding C++ director
1074 class. The reason for this difference is that user-defined subclasses
1075 may override or extend methods of the original class, so the director
1076 class is needed to route calls to these methods correctly. For
1077 unmodified proxy classes, all methods are ultimately implemented in C++
1078 so there is no need for the extra overhead involved with routing the
1079 calls through PHP.
1080 </p>
1081
1082 <H3><a name="Php_nn3_3"></a>29.3.3 Ownership and object destruction</H3>
1083
1084
1085 <p>
1086 Memory management issues are slightly more complicated with directors
1087 than for proxy classes alone. PHP instances hold a pointer to the
1088 associated C++ director object, and the director in turn holds a pointer
1089 back to the PHP object. By default, proxy classes own their C++ director
1090 object and take care of deleting it when they are garbage collected.
1091 </p>
1092
1093 <p>
1094 This relationship can be reversed by calling the special
1095 <tt>-&gt;thisown</tt> property of the proxy class. After setting this
1096 property to <tt>0</tt>, the director class no longer destroys the PHP
1097 object.  Assuming no outstanding references to the PHP object remain,
1098 the PHP object will be destroyed at the same time. This is a good thing,
1099 since directors and proxies refer to each other and so must be created
1100 and destroyed together. Destroying one without destroying the other will
1101 likely cause your program to segfault.
1102 </p>
1103
1104 <p>
1105 Here is an example:
1106 </p>
1107
1108 <div class="code">
1109 <pre>
1110 class Foo {
1111 public:
1112     ...
1113 };
1114 class FooContainer {
1115 public:
1116     void addFoo(Foo *);
1117     ...
1118 };
1119 </pre>
1120 </div>
1121
1122 <br>
1123
1124 <div class="targetlang">
1125 <pre>
1126 $c = new FooContainer();
1127 $a = new Foo();
1128 $a-&gt;thisown = 0;
1129 $c-&gt;addFoo($a);
1130 </pre>
1131 </div>
1132
1133 <p>
1134 In this example, we are assuming that FooContainer will take care of
1135 deleting all the Foo pointers it contains at some point.
1136 </p>
1137
1138 <H3><a name="Php_nn3_4"></a>29.3.4 Exception unrolling</H3>
1139
1140
1141 <p>
1142 With directors routing method calls to PHP, and proxies routing them
1143 to C++, the handling of exceptions is an important concern. By default, the
1144 directors ignore exceptions that occur during method calls that are
1145 resolved in PHP. To handle such exceptions correctly, it is necessary
1146 to temporarily translate them into C++ exceptions. This can be done with
1147 the %feature("director:except") directive. The following code should
1148 suffice in most cases:
1149 </p>
1150
1151 <div class="code">
1152 <pre>
1153 %feature("director:except") {
1154     if ($error == FAILURE) {
1155         throw Swig::DirectorMethodException();
1156     }
1157 }
1158 </pre>
1159 </div>
1160
1161 <p>
1162 This code will check the PHP error state after each method call from a
1163 director into PHP, and throw a C++ exception if an error occurred.  This
1164 exception can be caught in C++ to implement an error handler.
1165 Currently no information about the PHP error is stored in the
1166 Swig::DirectorMethodException object, but this will likely change in the
1167 future.
1168 </p>
1169
1170 <p>
1171 It may be the case that a method call originates in PHP, travels up to
1172 C++ through a proxy class, and then back into PHP via a director method.
1173 If an exception occurs in PHP at this point, it would be nice for that
1174 exception to find its way back to the original caller. This can be done
1175 by combining a normal %exception directive with the
1176 <tt>director:except</tt> handler shown above. Here is an example of a
1177 suitable exception handler:
1178 </p>
1179
1180 <div class="code">
1181 <pre>
1182 %exception {
1183     try { $action }
1184     catch (Swig::DirectorException &amp;e) { SWIG_fail; }
1185 }
1186 </pre>
1187 </div>
1188
1189 <p>
1190 The class Swig::DirectorException used in this example is actually a
1191 base class of Swig::DirectorMethodException, so it will trap this
1192 exception. Because the PHP error state is still set when
1193 Swig::DirectorMethodException is thrown, PHP will register the exception
1194 as soon as the C wrapper function returns.
1195 </p>
1196
1197 <H3><a name="Php_nn3_5"></a>29.3.5 Overhead and code bloat</H3>
1198
1199
1200 <p>
1201 Enabling directors for a class will generate a new director method for
1202 every virtual method in the class' inheritance chain. This alone can
1203 generate a lot of code bloat for large hierarchies. Method arguments
1204 that require complex conversions to and from target language types can
1205 result in large director methods. For this reason it is recommended that
1206 you selectively enable directors only for specific classes that are
1207 likely to be extended in PHP and used in C++.
1208 </p>
1209
1210 <p>
1211 Compared to classes that do not use directors, the call routing in the
1212 director methods does add some overhead. In particular, at least one
1213 dynamic cast and one extra function call occurs per method call from
1214 PHP. Relative to the speed of PHP execution this is probably completely
1215 negligible. For worst case routing, a method call that ultimately
1216 resolves in C++ may take one extra detour through PHP in order to ensure
1217 that the method does not have an extended PHP implementation. This could
1218 result in a noticeable overhead in some cases.
1219 </p>
1220
1221 <p>
1222 Although directors make it natural to mix native C++ objects with PHP
1223 objects (as director objects) via a common base class pointer, one
1224 should be aware of the obvious fact that method calls to PHP objects
1225 will be much slower than calls to C++ objects. This situation can be
1226 optimized by selectively enabling director methods (using the %feature
1227 directive) for only those methods that are likely to be extended in PHP.
1228 </p>
1229
1230 <H3><a name="Php_nn3_6"></a>29.3.6 Typemaps</H3>
1231
1232
1233 <p>
1234 Typemaps for input and output of most of the basic types from director
1235 classes have been written. These are roughly the reverse of the usual
1236 input and output typemaps used by the wrapper code. The typemap
1237 operation names are 'directorin', 'directorout', and 'directorargout'.
1238 The director code does not currently use any of the other kinds of
1239 typemaps.  It is not clear at this point which kinds are appropriate and
1240 need to be supported.
1241 </p>
1242
1243
1244 <H3><a name="Php_nn3_7"></a>29.3.7 Miscellaneous</H3>
1245
1246
1247 <p> Director typemaps for STL classes are mostly in place, and hence you
1248 should be able to use std::string, etc., as you would any other type.
1249 </p>
1250
1251 </body>
1252 </html>