PageRenderTime 81ms CodeModel.GetById 47ms app.highlight 22ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Doc/Manual/Php.html

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