1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <!-- Hand crafted HTML -->
5 <title>SWIG and PHP</title>
6 <link rel="stylesheet" type="text/css" href="style.css">
9 <body bgcolor="#ffffff">
10 <H1><a name="Php"></a>29 SWIG and PHP</H1>
12 <div class="sectiontoc">
14 <li><a href="#Php_nn1">Generating PHP Extensions</a>
16 <li><a href="#Php_nn1_1">Building a loadable extension</a>
17 <li><a href="#Php_nn1_3">Using PHP Extensions</a>
19 <li><a href="#Php_nn2">Basic PHP interface</a>
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>
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>
33 <li><a href="#Php_nn2_7">PHP Pragmas, Startup and Shutdown code</a>
35 <li><a href="#Php_nn3">Cross language polymorphism</a>
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>
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.
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.
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
78 <H2><a name="Php_nn1"></a>29.1 Generating PHP Extensions</H2>
82 To build a PHP extension, run swig using the <tt>-php</tt> option as
86 <div class="code"><pre>
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.
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.
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>.
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
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.
125 <H3><a name="Php_nn1_1"></a>29.1.1 Building a loadable extension</H3>
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):
135 <div class="code"><pre>
136 gcc `php-config --includes` -fpic -c example_wrap.c
137 gcc -shared example_wrap.o -o example.so
140 <H3><a name="Php_nn1_3"></a>29.1.2 Using PHP Extensions</H3>
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
149 <div class="code"><pre>
150 extension=/path/to/modulename.so
154 Alternatively, you can load it explicitly only for scripts which need it
158 <div class="code"><pre>
159 dl("/path/to/modulename.so"); // Load the module
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:
167 <div class="code"><pre>
168 include("example.php");
171 <H2><a name="Php_nn2"></a>29.2 Basic PHP interface</H2>
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.
181 <H3><a name="Php_nn2_1"></a>29.2.1 Constants</H3>
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,
192 <div class="code"><pre>
197 %constant int E = 2.71828
202 you can access the constants in your php script like this,
205 <div class="code"><pre>
206 include("example.php");
208 echo "PI = " . PI . "\n";
210 echo "E = " . E . "\n";
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,
221 <div class="code"><pre>
224 #define EASY_TO_MISPELL 0
229 accessed incorrectly in PHP,
234 include("example.php");
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!
253 The second 'feature' is that although constants are case sensitive (by
254 default), you cannot declare a constant twice with alternative
273 include("example.php");
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
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. )
306 <H3><a name="Php_nn2_2"></a>29.2.2 Global Variables</H3>
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.
315 <div class="code"><pre>
321 zend_printf("seki is now %f\n",seki);
327 is accessed as follows:
330 <div class="code"><pre>
331 include("example.php");
333 seki_set( seki_get() * 2); # The C variable is now 4.
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.
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
352 At this time SWIG does not support custom accessor methods.
355 <H3><a name="Php_nn2_3"></a>29.2.3 Functions</H3>
359 C functions are converted into PHP functions. Default/optional arguments are
360 also allowed. An interface file like this :
363 <div class="code"><pre>
366 double bar(double, double b = 3.0);
371 Will be accessed in PHP like this :
374 <div class="code"><pre>
375 include("example.php");
378 $c = bar(3.5); # Use default argument for 2nd parameter
382 <!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
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:
388 <div class="code"><pre>
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
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.
408 <H3><a name="Php_nn2_4"></a>29.2.4 Overloading</H3>
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>.
420 <!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
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:
429 <div class="code"><pre>
431 void doit( double i );
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>.
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.
449 It should be noted that <tt>SWIGTYPE</tt> references and pointers will
450 not be silently converted. So these two functions:
453 <div class="code"><pre>
454 void doit( const Vector & );
459 Cause less confusion and <tt>doit("2");</tt> will invoke the function
460 taking the integer argument.
464 <H3><a name="Php_nn2_5"></a>29.2.5 Pointers and References</H3>
468 Pointers to C/C++ objects are represented
469 as PHP resources, rather like MySQL connection handles.
473 There are multiple ways to wrap pointers to simple types. Given the
477 <div class="code"><pre>
478 void add( int *in1, int *in2, int *result);
482 One can include <b>cpointer.i</b> to generate PHP wrappers to <tt>int
486 <div class="code"><pre>
488 %include "cpointer.i"
489 %pointer_functions(int,intp)
491 void add( int *in1, int *in2, int *result);
495 This will result in the following usage in PHP:
498 <div class="code"><pre>
501 include("example.php");
507 add( $in1, $in2, $result );
509 echo "The sum " . intp_value($in1) . " + " . intp_value($in2) . " = " . intp_value( $result) . "\n";
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.
520 <div class="code"><pre>
522 %include "typemaps.i"
524 void add( int *INPUT, int *INPUT, int *OUTPUT);
529 This will result in the following usage in PHP:
532 <div class="code"><pre>
535 include("example.php");
539 $result= add($in1,$in2); # Note using variables for the input is unnecessary.
541 echo "The sum $in1 + $in2 = $result\n";
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.
552 <div class="code"><pre>
554 %include "phppointers.i"
556 void add( int *REF, int *REF, int *REF);
561 This will result in the following usage in PHP:
564 <div class="code"><pre>
567 include("example.php");
572 add(&$in1,&$in2,&$result);
574 echo "The sum $in1 + $in2 = $result\n";
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.
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.
596 <H3><a name="Php_nn2_6"></a>29.2.6 Structures and C++ classes</H3>
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.
609 <div class="code"><pre>
626 Would be used in the following way from PHP5:
629 <div class="code"><pre>
631 require "vector.php";
638 echo "Magnitude of ($v->x,$v->y,$v->z) = " . $v->magnitude() . "\n";
640 $v = NULL; # destructor called.
647 # $c destructor called when $c goes out of scope.
652 Member variables and methods are accessed using the <tt>-></tt> operator.
655 <H4><a name="Php_nn2_6_1"></a>29.2.6.1 Using <tt>-noproxy</tt></H4>
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:
665 <div class="code"><pre>
667 Vector_x_set($obj,$d);
669 Vector_y_set($obj,$d);
671 Vector_z_set($obj,$d);
673 Vector_magnitude($obj);
675 Complex_re_set($obj,$d);
676 Complex_re_get($obj);
677 Complex_im_set($obj,$d);
678 Complex_im_get($obj);
681 <H4><a name="Php_nn2_6_2"></a>29.2.6.2 Constructors and Destructors</H4>
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.
693 Because PHP uses reference counting to manage resources, simple
694 assignment of one variable to another such as:
697 <div class="code"><pre>
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.
708 One can force execution of the copy constructor by using:
710 <div class="code"><pre>
711 $o_copy = new Object($o);
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
722 <H4><a name="Php_nn2_6_3"></a>29.2.6.3 Static Member Variables</H4>
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
733 <div class="code"><pre>
743 would be accessed in PHP as,
746 <div class="code"><pre>
747 include("example.php");
749 echo "There has now been " . Ko::threats() . " threats\n";
754 To set the static member variable, pass the value as the argument to the class
758 <div class="code"><pre>
762 echo "There has now been " . Ko::threats() . " threats\n";
765 <H4><a name="Php_nn2_6_4"></a>29.2.6.4 Static Member Functions</H4>
769 Static member functions are supported in PHP using the
770 <tt>class::function()</tt> syntax. For example
773 <div class="code"><pre>
776 static void threats();
780 would be executed in PHP as,
781 <div class="code"><pre>
782 include("example.php");
787 <H3><a name="Php_nn2_7"></a>29.2.7 PHP Pragmas, Startup and Shutdown code</H3>
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
796 <div class="code"><pre>
799 # This code is inserted into example.php
800 echo \"example.php execution\\n\";
805 Results in the following in "example.php"
808 <div class="code"><pre>
809 # This code is inserted into example.php
810 echo "example.php execution\n";
814 The <b>include</b> pragma is a short cut to add include statements to
815 the example.php file.
818 <div class="code"><pre>
821 include \"include.php\";
823 %pragma(php) include="include.php" // equivalent.
827 The <b>phpinfo</b> pragma inserts code in the
828 <tt>PHP_MINFO_FUNCTION</tt> which is called from PHP's
832 <div class="code"><pre>
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();
844 To insert code into the <tt>PHP_MINIT_FUNCTION</tt>, one can use
845 either <tt>%init</tt> or <tt>%minit</tt>.
848 <div class="code"><pre>
851 zend_printf("Inserted into PHP_MINIT_FUNCTION\n");
854 zend_printf("Inserted into PHP_MINIT_FUNCTION\n");
859 To insert code into the <tt>PHP_MSHUTDOWN_FUNCTION</tt>, one can use
860 either <tt>%init</tt> or <tt>%minit</tt>.
863 <div class="code"><pre>
866 zend_printf("Inserted into PHP_MSHUTDOWN_FUNCTION\n");
871 The <tt>%rinit</tt> and <tt>%rshutdown</tt> statements insert code
872 into the request init and shutdown code respectively.
875 <H2><a name="Php_nn3"></a>29.3 Cross language polymorphism</H2>
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.
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.
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
910 <H3><a name="Php_nn3_1"></a>29.3.1 Enabling directors</H3>
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:
921 %module(directors="1") modulename
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:
934 // generate directors for all classes that have virtual methods
935 %feature("director");
937 // generate directors for all virtual methods in class Foo
938 %feature("director") Foo;
940 // generate a director for just Foo::bar()
941 %feature("director") Foo::bar;
946 You can use the %feature("nodirector") directive to turn off
947 directors for specific classes or methods. So for example,
952 %feature("director") Foo;
953 %feature("nodirector") Foo::bar;
958 will generate directors for all virtual methods of class Foo except
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()):
970 %feature("director") Foo;
978 class Bar: public Foo {
980 virtual void three();
986 then at the PHP side you can define
989 <div class="targetlang">
991 require("mymodule.php");
993 class MyFoo extends Foo {
995 print "one from php\n";
1002 <H3><a name="Php_nn3_2"></a>29.3.2 Director classes</H3>
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.
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.
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).
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
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>->_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
1082 <H3><a name="Php_nn3_3"></a>29.3.3 Ownership and object destruction</H3>
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.
1094 This relationship can be reversed by calling the special
1095 <tt>->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.
1114 class FooContainer {
1124 <div class="targetlang">
1126 $c = new FooContainer();
1134 In this example, we are assuming that FooContainer will take care of
1135 deleting all the Foo pointers it contains at some point.
1138 <H3><a name="Php_nn3_4"></a>29.3.4 Exception unrolling</H3>
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:
1153 %feature("director:except") {
1154 if ($error == FAILURE) {
1155 throw Swig::DirectorMethodException();
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
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:
1184 catch (Swig::DirectorException &e) { SWIG_fail; }
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.
1197 <H3><a name="Php_nn3_5"></a>29.3.5 Overhead and code bloat</H3>
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++.
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.
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.
1230 <H3><a name="Php_nn3_6"></a>29.3.6 Typemaps</H3>
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.
1244 <H3><a name="Php_nn3_7"></a>29.3.7 Miscellaneous</H3>
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.