summaryrefslogtreecommitdiff
path: root/Doc/Manual/Php.html
blob: 49d0474f7e4742c6c3ce6477037bc51529b0ade4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and PHP</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>

<body bgcolor="#ffffff">
<H1><a name="Php">32 SWIG and PHP</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Php_nn1">Generating PHP Extensions</a>
<ul>
<li><a href="#Php_nn1_1">Building a loadable extension</a>
<li><a href="#Php_nn1_3">Using PHP Extensions</a>
</ul>
<li><a href="#Php_nn2">Basic PHP interface</a>
<ul>
<li><a href="#Php_nn2_1">Constants</a>
<li><a href="#Php_nn2_2">Global Variables</a>
<li><a href="#Php_nn2_3">Functions</a>
<li><a href="#Php_nn2_4">Overloading</a>
<li><a href="#Php_nn2_5">Pointers and References</a>
<li><a href="#Php_nn2_6">Structures and C++ classes</a>
<ul>
<li><a href="#Php_nn2_6_1">Using -noproxy</a>
<li><a href="#Php_nn2_6_2">Constructors and Destructors</a>
<li><a href="#Php_nn2_6_3">Static Member Variables</a>
<li><a href="#Php_nn2_6_4">Static Member Functions</a>
<li><a href="#Php_nn2_6_5">Specifying Implemented Interfaces</a>
<li><a href="#Php_nn2_6_6">Dynamic Properties</a>
</ul>
<li><a href="#Php_nn2_7">PHP Pragmas, Startup and Shutdown code</a>
</ul>
<li><a href="#Php_nn3">Cross language polymorphism</a>
<ul>
<li><a href="#Php_nn3_1">Enabling directors</a>
<li><a href="#Php_nn3_2">Director classes</a>
<li><a href="#Php_nn3_3">Ownership and object destruction</a>
<li><a href="#Php_nn3_4">Exception unrolling</a>
<li><a href="#Php_nn3_5">Overhead and code bloat</a>
<li><a href="#Php_nn3_6">Typemaps</a>
<li><a href="#Php_nn3_7">Miscellaneous</a>
</ul>
</ul>
</div>
<!-- INDEX -->



<p>
In this chapter, we discuss SWIG's support of PHP.  Currently any PHP7 or PHP8
release should work.
</p>

<p>
Support for PHP7 was added in SWIG 3.0.11 and for PHP8 in 4.1.0.
Support for PHP5 was removed in SWIG 4.0.0 and support for PHP4 was removed in
SWIG 1.3.37.  There never was a PHP6 release.
</p>

<p>
In order to use this module, you will need to have a copy of the PHP
include files to compile the SWIG generated C/C++ sources.  If you installed
PHP from a binary package, you may need to install a "php-dev" or "php-devel"
package for these to be installed.  You can find out where these files are
by running <tt>php-config --includes</tt>.  To use the built PHP module you
will need either the php binary or the Apache php module. If you want to build
your extension into php directly, you will need the complete PHP source tree
available.
</p>

<H2><a name="Php_nn1">32.1 Generating PHP Extensions</a></H2>


<p>
To build a PHP extension, run swig using the <tt>-php7</tt> option as follows
(<tt>-php</tt> is also supported and currently is an alias for <tt>-php7</tt>
but prior to SWIG 4.0.0 it was an alias for <tt>-php5</tt>):
</p>

<div class="code"><pre>
swig -php7 example.i
</pre></div>

<p>
This will produce 2 files: example_wrap.c and php_example.h.
The first file, <tt>example_wrap.c</tt> contains all of
the C code needed to build a PHP extension. The second file,
<tt>php_example.h</tt> contains the header information needed if
you wish to statically link the extension into the php interpreter.
</p>

<p>
If the interface file uses <tt>%pragma(php) include=</tt>... or
<tt>%pragma(php) code=</tt>... then SWIG will also generate a third file,
<tt>example.php</tt> to contain what these specify.  In SWIG &lt; 4.1.0,
this third file was always generated as it defined the PHP classes, etc
(but this is now done via C code in <tt>example_wrap.c</tt>) and also
contained code to dynamically load the extension (but this used the
PHP <tt>dl()</tt> function, which isn't recommended nowadays).
</p>

<p>
SWIG can generate PHP extensions from C++ libraries as well when
given the <tt>-c++</tt> option.  The support for C++ is discussed in
more detail in <a href="#Php_nn2_6">section 27.2.6</a>.  The generated
C++ wrapper will be called example_wrap.cxx.  You can specify a
different extension for the C++ wrapper using <tt>-cppext</tt> -
e.g. if you want example_wrap.cc use <tt>-cppext cc</tt>.
</p>

<p>
The usual (and recommended) way is to build the extension as a separate
dynamically loaded module (which is supported by all modern operating
systems).
</p>

<p>
It is also possible to rebuild PHP from source so that your module is
statically linked into the php executable/library.  This is a lot more
work, and also requires a full rebuild of PHP to update your module,
and it doesn't play nicely with package system.  We don't recommend
this approach, or provide explicit support for it.
</p>

<H3><a name="Php_nn1_1">32.1.1 Building a loadable extension</a></H3>


<p>
To build your module as a dynamically loadable extension, use compilation
commands like these (if you aren't using GCC, the commands will be different,
and there may be some variation between platforms - these commands should at
least work for Linux though):
</p>

<div class="code"><pre>
        gcc `php-config --includes` -fpic -c example_wrap.c example.c
        gcc -shared example_wrap.o example.o -o example.so
</pre></div>

<H3><a name="Php_nn1_3">32.1.2 Using PHP Extensions</a></H3>


<p>
To test the extension from a PHP script, you first need to tell PHP to
load it.  Assuming you're using PHP 7.2 or higher, the recommended (and
simplest!) way to do this is to copy it to PHP's default extension directory
and add a line like this to the <tt>[PHP]</tt> section of <tt>php.ini</tt>:
</p>

<div class="code"><pre>
        extension=modulename
</pre></div>

<p>
PHP &lt; 7.2 doesn't support loading by just the module name, so you need
to specify the filename of the module to be specified, which varies
between platforms.  And for any PHP version, if the module is not in PHP's
default extension directory, you also need to specify the path, for example:
</p>

<div class="code"><pre>
        extension=/path/to/modulename.so
</pre></div>

<p>
If you're using the PHP CLI SAPI it's possible (but not recommended) to use the
<a href="https://www.php.net/manual/en/function.dl.php">dl() function</a> to
load an extension at run time, by adding a line like this to the start of each
PHP script which uses your extension:
</p>

<div class="code"><pre>
        dl("/path/to/modulename.so"); // Load the module
</pre></div>

<p>
But to do this portably you need to take into account that pathnames and the
filename extension vary by platform, and for security reasons PHP no longer
supports <tt>dl()</tt> when running PHP through a webserver.  Overall it's
better to instead use <tt>extension</tt> in <tt>php.ini</tt> as described
above.
</p>

<H2><a name="Php_nn2">32.2 Basic PHP interface</a></H2>


<p>
It is important to understand that PHP uses a single global namespace
into which all symbols from extension modules are loaded.  It is quite
possible for names of symbols in one extension module to clash with
other symbols unless care is taken to <tt>%rename</tt> them.  At present
SWIG doesn't have support for generating wrappers which make use of PHP's
namespace feature.
</p>

<H3><a name="Php_nn2_1">32.2.1 Constants</a></H3>


<p>
These work in much the same way as in C/C++.  Constants can be defined
by using either the normal C pre-processor declarations, or the
<tt>%constant</tt> SWIG directive.  These will then be available from
your PHP script as a PHP constant, (i.e. no dollar sign is needed to
access them.) For example, with a swig interface file like this,
</p>

<div class="code"><pre>
%module example

#define PI 3.14159

%constant int E  = 2.71828
</pre>
</div>

<p>
you can access the constants in your PHP script like this,
</p>

<div class="code"><pre>
echo "PI = " . PI . "\n";
echo "E = " . E . "\n";
</pre>
</div>

<p>
There's one peculiarity of how constants work in PHP prior to PHP 8
which it is useful to note (this is not specific to SWIG though) - if you try
to use an undeclared constant, PHP will emit a warning (or a notice in PHP 7.1
and earlier) and then expand the constant to a string version of the constant's
name.  Unfortunately it is easy to miss the warning message if you're using PHP
in a webserver as it will probably end up in error.log or similar.  PHP 8.0
made this an error.
</p>

<p>
For example,
</p>

<div class="code"><pre>
%module example

#define EASY_TO_MISPELL 0
</pre>
</div>

<p>
accessed incorrectly in PHP,
</p>

<div class="code">
<pre>
if(EASY_TO_MISPEL) {
  ...
} else {
  ...
}

</pre>
</div>

<p>
The mis-spelled constant will become the string 'EASY_TO_MISPEL', which
is treated as true by the if test, when the value of the intended constant
would be treated as false!
</p>

<H3><a name="Php_nn2_2">32.2.2 Global Variables</a></H3>


<p>
Because PHP does not provide a mechanism to intercept access and
assignment of global variables, global variables are supported through
the use of automatically generated accessor functions.
</p>

<div class="code"><pre>
%module example;

%inline %{
  double seki = 2;
  void print_seki() {
    zend_printf("seki is now %f\n", seki);
  }
%}
</pre></div>

<p>
is accessed as follows:
</p>

<div class="code"><pre>
print seki_get();
seki_set( seki_get() * 2); # The C variable is now 4.
print seki_get();
</pre></div>

<p>
SWIG supports global variables of all C datatypes including pointers
and complex objects.  To support additional types, you just need to
supply the standard <tt>in</tt> and <tt>out</tt> typemaps, which get
used because of the wrapping as <tt>_get()</tt> and <tt>_set()</tt>
functions.
</p>

<p>
SWIG honors the <tt>%immutable</tt> modifier by not generating a
<tt>_set</tt> method (so attempting to call it will give a PHP fatal
error).  A <tt>_get</tt> method is still generated so this provides read-only
access to the variable from the PHP script.
</p>

<p>
At this time SWIG does not support custom accessor methods.
</p>

<H3><a name="Php_nn2_3">32.2.3 Functions</a></H3>


<p>
C functions are converted into PHP functions. Default/optional arguments are
also allowed. An interface file like this :
</p>

<div class="code"><pre>
%module example
int foo(int a);
double bar(double, double b = 3.0);
...
</pre></div>

<p>
Will be accessed in PHP like this :
</p>

<div class="code"><pre>
$a = foo(2);
$b = bar(3.5, -1.5);
$c = bar(3.5);  # Use default argument for 2nd parameter

</pre></div>

<p>
SWIG generates PHP type declarations for function parameters and return
types for PHP 8 and later (we don't try to support PHP 7's more limited type
declarations and the generated wrappers compiled for PHP 7 will not have any
type declarations).
</p>

<p>
You can control the generation of PHP type declarations using
the "php:type" %feature.  This has three settings:
</p>

<ul>
    <li> <p>If unset or set to "0" then no type declarations are generated, e.g.: <tt>%feature("php:type", "0");</tt>
      </p>
    </li>
    <li> <p>If set to "1" then type declarations are generated for both parameters and return types, e.g.: <tt>%feature("php:type", "1");</tt>
      </p></li>
      <li> <p>The default setting is "compat", which is the same as "1" except no
      return type declarations are generated for virtual methods for which
      directors are enabled.  This provides better compatibility for PHP
      subclasses of wrapped virtual methods in existing SWIG-generated bindings, e.g.: <tt>%feature("php:type", "compat");</tt>
      </p></li>
</ul>

<p>
If you have an existing PHP interface and are upgrading to SWIG &gt;= 4.1.0
then the default "compat" setting should work well.
</p>

<p>
If you're writing a new set of bindings and <b>only targeting PHP8 or newer</b>
then enabling type declarations everywhere probably makes sense.  It will
only actually make a difference if you enable directors and are wrapping C++
classes with virtual methods, but doing it anyway means you won't forget to if
the code you are wrapping later evolves to have such classes and methods.
</p>

<p>
The type declaration information will make the generated source code and
compiler extension module larger, so you might want to turn off type
declarations if keeping these small is important to you.  If you find you
need to turn off type declarations to fix a problem, please let us know
via our github issue tracker.
</p>

<p>
Note that being a SWIG feature this can be specified globally (like above) or
per class, per method, etc.  See the <a
href="Customization.html#Customization_features">%feature directives</a>
section for full details of how to control at a fine-grained level.
</p>

<p>
The PHP type information is specified via a "phptype" attribute on "in" and
"out" typemaps, and these have been added for all the typemaps we supply for
PHP.  We don't currently support this for "argout" templates, but probably
will in a future version.
</p>

<p>
If you have written custom SWIG typemaps for PHP and want to add PHP type
declarations, then the syntax is very like how you'd specify the type in
PHP code, e.g. <tt>%typemap(in, phptype="int|string|Foo")</tt> means the
typemap accepts a PHP int or string or an object of class Foo,
<tt>%typemap(in, phptype="?int")</tt> means a PHP int or NULL, etc.
As well as the standard PHP type declaration types, SWIG also understands the
special type "SWIGTYPE" as an entry in phptype, which means the PHP type
corresponding to the type that this typemap matched on - for a object this
will give you the PHP class for the object, and for a pointer to a non-class
type it will give you the name of the PHP class SWIG created for that
pointer type.
</p>

<!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
<p>
Because PHP is a dynamically typed language, the default typemaps
used for simple types will attempt to coerce the arguments into the appropriate type.  That is the following invocations are equivalent:
</p>

<div class="code"><pre>
$a = foo(2);
$a = foo("2");
$a = foo(2.0);
</pre></div>

<p>
Functions are invoked using pass by value semantics like all of PHP.
This means the conversion which automatically takes place when
invoking a swig wrapped method does not change the native type of the
argument variable.
</p>
<div class="code"><pre>
$s = "2 A string representing two";
$a = foo($s);  # invokes 'foo(2)';
print $s;      # The value of $s was not changed.
</pre></div>
-->


<H3><a name="Php_nn2_4">32.2.4 Overloading</a></H3>


<p>
Although PHP does not support overloading functions natively, swig
will generate dispatch functions which will use <tt>%typecheck</tt>
typemaps to allow overloading.  This dispatch function's operation and
precedence is described in <a
href="SWIGPlus.html#SWIGPlus_overloaded_methods">Overloaded functions and methods</a>.
</p>

<!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
<p>
Because PHP is a dynamically typed language, simple values can be
silently converted from one type to another.  For example, integers,
doubles and strings silently convert to each other depending on
context.  This situation make overloading slightly problematic because
given the following function:
</p>

<div class="code"><pre>
void doit( int i );
void doit( double i );
</pre></div>

<p>
it is questionable which to invoke when <tt>doit("2");</tt> is used in
PHP.  The string <tt>"2"</tt> simultaneously represents the integer
<tt>2</tt> and the double <tt>2.0</tt>.
</p>

<p>
In order to provide the most natural experience to PHP programmers,
the default <tt>%typecheck</tt> implemented in <tt>php.swg</tt>
allows any simple type (integer, double, string) in PHP to be used for
any simple C type (int, double, char *).  The function selected then
depends only on the argument type precedence defined by SWIG.
</p>

<p>
It should be noted that <tt>SWIGTYPE</tt> references and pointers will
not be silently converted.  So these two functions:
</p>

<div class="code"><pre>
void doit( const Vector &amp; );
void doit( int i );
</pre></div>

<p>
Cause less confusion and <tt>doit("2");</tt> will invoke the function
taking the integer argument.
</p>
-->

<H3><a name="Php_nn2_5">32.2.5 Pointers and References</a></H3>


<p>
Since SWIG 4.1.0, SWIG wraps C/C++ classes directly with PHP objects.
Pointers to other types are also wrapped as PHP objects - mostly this is an
implementation detail, but it's visible from PHP via <tt>is_object()</tt> and
similar.  In earlier SWIG versions, PHP resources were used to wrap both
classes and pointers to other types.
</p>

<p>
There are multiple ways to wrap pointers to simple types.  Given the
following C method:
</p>

<div class="code"><pre>
  void add( int *in1, int *in2, int *result);
</pre></div>

<p>
One can include <b>cpointer.i</b> to generate PHP wrappers to <tt>int
*</tt>.
</p>

<div class="code"><pre>
%module example
%include "cpointer.i"
%pointer_functions(int, intp)

void add( int *in1, int *in2, int *result);
</pre></div>

<p>
This will result in the following usage in PHP:
</p>

<div class="code"><pre>
&lt;?php

$in1=copy_intp(3);
$in2=copy_intp(5);
$result=new_intp();

add( $in1, $in2, $result );

echo "The sum " . intp_value($in1) . " + " . intp_value($in2) . " = " . intp_value( $result) . "\n";
</pre></div>

<p>
An alternative would be to use the include <b>typemaps.i</b> which
defines named typemaps for INPUT, OUTPUT and INOUT variables.  One
needs to either <tt>%apply</tt> the appropriate typemap or adjust the
parameter names as appropriate.
</p>

<div class="code"><pre>
%module example
%include "typemaps.i"

void add( int *INPUT, int *INPUT, int *OUTPUT);

</pre></div>

<p>
This will result in the following usage in PHP:
</p>

<div class="code"><pre>
&lt;?php

$in1 = 3;
$in2 = 5;
$result= add($in1, $in2);  # Note using variables for the input is unnecessary.

echo "The sum $in1 + $in2 = $result\n";
</pre></div>

<p>
Because PHP has a native concept of reference, it may seem more natural
to the PHP developer to use references to pass pointers.  To enable
this, one needs to include <b>phppointers.i</b> which defines the
named typemap REF.
</p>

<p>
In case you write your own typemaps, SWIG supports an attribute called
<tt>byref</tt>: if you set that, then SWIG will make sure that the generated
wrapper function will want the input parameter as a reference.
</p>

<div class="code"><pre>
%module example
%include "phppointers.i"

void add( int *REF, int *REF, int *REF);

</pre></div>

<p>
This will result in the following usage in PHP:
</p>

<div class="code"><pre>
&lt;?php

$in1 = 3;
$in2 = 5;
$result = 0;
add($in1, $in2, $result);

echo "The sum $in1 + $in2 = $result\n";
</pre></div>

<p>
It is important to note that a php variable which is NULL when passed
by reference would end up passing a NULL pointer into the function.
In PHP, an unassigned variable (i.e. where the first reference to the
variable is not an assignment) is
NULL.  In the above example, if any of the three variables had not
been assigned, a NULL pointer would have been passed into
<tt>add</tt>.  Depending on the implementation of the function, this
may or may not be a good thing.
</p>

<p>
We chose to allow passing NULL pointers into functions because that is
sometimes required in C libraries.  A NULL pointer can be created in
PHP in a number of ways: by using <tt>unset</tt> on an existing
variable, or assigning <tt>NULL</tt> to a variable.
</p>

<H3><a name="Php_nn2_6">32.2.6 Structures and C++ classes</a></H3>


<p>
SWIG defaults to wrapping C++ structs and classes with PHP classes.
Since SWIG 4.1.0, this is done entirely via PHP's C API - earlier SWIG
versions generated a PHP wrapper script which defined proxy classes
which called a set of flat functions which actually wrapped the C++ class.
</p>

<p>
If you don't want the class wrappers, you can pass the command-line option
"-noproxy" in which case you'll get C++ classes wrapped as flat functions
as described below.
</p>

<p>
This interface file
</p>

<div class="code"><pre>
%module vector

class Vector {
public:
  double x, y, z;
  Vector();
  ~Vector();
  double magnitude();
};

struct Complex {
 double re, im;
};
</pre></div>

<p>
Would be used in the following way from PHP:
</p>

<div class="code"><pre>
&lt;?php

  $v = new Vector();
  $v-&gt;x = 3;
  $v-&gt;y = 4;
  $v-&gt;z = 5;

  echo "Magnitude of ($v-&gt;x, $v-&gt;y, $v-&gt;z) = " . $v-&gt;magnitude() . "\n";

  $v = NULL;   # destructor called.

  $c = new Complex();

  $c-&gt;re = 0;
  $c-&gt;im = 0;

  # $c destructor called when $c goes out of scope.
</pre></div>

<p>
Member variables and methods are accessed using the <tt>-&gt;</tt> operator.
</p>

<H4><a name="Php_nn2_6_1">32.2.6.1 Using -noproxy</a></H4>


<p>
The <tt>-noproxy</tt> option flattens the object structure and
generates collections of named functions.  The above example results
in the following PHP functions:
</p>

<div class="code"><pre>
new_Vector();
Vector_x_set($obj, $d);
Vector_x_get($obj);
Vector_y_set($obj, $d);
Vector_y_get($obj);
Vector_z_set($obj, $d);
Vector_z_get($obj);
Vector_magnitude($obj);
new_Complex();
Complex_re_set($obj, $d);
Complex_re_get($obj);
Complex_im_set($obj, $d);
Complex_im_get($obj);
</pre></div>

<H4><a name="Php_nn2_6_2">32.2.6.2 Constructors and Destructors</a></H4>


<p>
The constructor is called when <tt>new Object()</tt> (or
<tt>new_Object()</tt> if using <tt>-noproxy</tt>) is used to create an
instance of the object. If multiple constructors are defined for an
object, function overloading will be used to determine which
constructor to execute.
</p>

<p>
Because PHP uses reference counting, simple assignment of one variable to
another such as:
</p>

<div class="code"><pre>
$ref = $v;
</pre></div>

<p>
causes the symbol <tt>$ref</tt> to refer to the same underlying object
as <tt>$v</tt>.  This does not result in a call to the C++ copy
constructor or copy assignment operator.
</p>

<p>
One can force execution of the copy constructor by using:
</p>
<div class="code"><pre>
$o_copy = new Object($o);
</pre></div>

<p>
Destructors are automatically called when all variables referencing
the instance are reassigned or go out of scope.  The destructor is not
available to be called manually.  To force a destructor to be called
the programmer can either reassign the variable or call
<tt>unset($v)</tt>
</p>

<H4><a name="Php_nn2_6_3">32.2.6.3 Static Member Variables</a></H4>


<p>
Static member variables in C++ are not wrapped as such in PHP
as it does not appear to be possible to intercept accesses to such variables.
Therefore, static member variables are
wrapped using a class function with the same name, which
returns the current value of the class variable. For example
</p>

<div class="code"><pre>
%module example

class Ko {
  static int threats;
};

</pre></div>

<p>
would be accessed in PHP as,
</p>

<div class="code"><pre>
echo "There have now been " . Ko::threats() . " threats\n";

</pre></div>

<p>
To set the static member variable, pass the value as the argument to the class
function, e.g.
</p>

<div class="code"><pre>

Ko::threats(10);

echo "There have now been " . Ko::threats() . " threats\n";

</pre></div>
<H4><a name="Php_nn2_6_4">32.2.6.4 Static Member Functions</a></H4>


<p>
Static member functions are supported in PHP using the
<tt>class::function()</tt> syntax.  For example
</p>

<div class="code"><pre>
%module example
class Ko {
  static void threats();
};
</pre></div>

<p>
would be executed in PHP as
</p>

<div class="code"><pre>
Ko::threats();
</pre></div>


<H4><a name="Php_nn2_6_5">32.2.6.5 Specifying Implemented Interfaces</a></H4>


<p>
PHP supports the concept of abstract interfaces which a class can implement.
Since SWIG 3.0.3, you can tell SWIG that a wrapped class (for example
<code>MyIterator</code>) implements the <code>Iterator</code> interface like
so:
</p>

<div class="code"><pre>
%typemap("phpinterfaces") MyIterator "Iterator"
</pre></div>

<p>
If there are multiple interfaces, just list them separated by commas.
</p>


<H4><a name="Php_nn2_6_6">32.2.6.6 Dynamic Properties</a></H4>


<p>
Historically PHP has supported dynamic class properties and SWIG
has implemented them too (because we implement the magic <tt>__get()</tt>,
<tt>__set()</tt> and <tt>__isset()</tt> methods we need to include explicit
handling).
</p>

<p>
PHP 8.2 <a
href="https://wiki.php.net/rfc/deprecate_dynamic_properties">deprecates
dynamic class properties</a> - initially they'll warn, and apparently they'll
not work by default in PHP 9.0.
</p>

<p>
In PHP code dynamic properties can be enabled for a class by
marking that class with the attribute <tt>#[AllowDynamicProperties]</tt>.
</p>
	
<p>
To follow this PHP change, as of SWIG 4.1.0 you now need enable dynamic
properties for any classes you want to support them.  To enable for class
<tt>Foo</tt>:
</p>

<div class="code"><pre>
%feature("php:allowdynamicproperties", 1) Foo;
</pre></div>

<p>
or to enable them for all wrapped classes:
</p>

<div class="code"><pre>
%feature("php:allowdynamicproperties", 1);
</pre></div>

<p>
Note that unknown features are ignored, so you can add use these
unconditionally in your interface file and it'll work with older SWIG too.
</p>


<H3><a name="Php_nn2_7">32.2.7 PHP Pragmas, Startup and Shutdown code</a></H3>


<p>
You can get SWIG to generate an "example.php" file by specifying
the code to put in it using the <b>code</b> pragma.
</p>

<div class="code"><pre>
%module example
%pragma(php) code="
# This code is inserted into example.php
echo \"example.php execution\\n\";
"
</pre></div>

<p>
Results in the following in "example.php"
</p>

<div class="code"><pre>
# This code is inserted into example.php
echo "example.php execution\n";
</pre></div>

<p>
The <b>version</b> pragma can be used to add version to generated PHP extension module. The version is inserted in the zend_module_entry block.
</p>

<div class="code"><pre>
%module example
%pragma(php) version="1.5"
</pre></div>

<p>
The <b>include</b> pragma is a short cut to add include statements to
the example.php file.
</p>

<div class="code"><pre>
%module example
%pragma(php) code="
include \"include.php\";
"
%pragma(php) include="include.php"   // equivalent.
</pre></div>

<p>
The <b>phpinfo</b> pragma inserts code in the
<tt>PHP_MINFO_FUNCTION</tt> which is called from PHP's
phpinfo() function.
</p>

<div class="code"><pre>
%module example;
%pragma(php) phpinfo="
  zend_printf("An example of PHP support through SWIG\n");
  php_info_print_table_start();
  php_info_print_table_header(2, \"Directive\", \"Value\");
  php_info_print_table_row(2, \"Example support\", \"enabled\");
  php_info_print_table_end();
"
</pre></div>

<p>
To insert code into the <tt>PHP_MINIT_FUNCTION</tt>, one can use
either <tt>%init</tt> or <tt>%minit</tt>.
</p>

<div class="code"><pre>
%module example;
%init {
  zend_printf("Inserted into PHP_MINIT_FUNCTION\n");
}
%minit {
  zend_printf("Inserted into PHP_MINIT_FUNCTION\n");
}
</pre></div>

<p>
To insert code into the <tt>PHP_MSHUTDOWN_FUNCTION</tt>, one can use
either <tt>%shutdown</tt> or <tt>%mshutdown</tt>.
</p>

<div class="code"><pre>
%module example;
%mshutdown {
  zend_printf("Inserted into PHP_MSHUTDOWN_FUNCTION\n");
}
</pre></div>

<p>
The <tt>%rinit</tt> and <tt>%rshutdown</tt> statements are very similar but insert code
into the request init (PHP_RINIT_FUNCTION) and request shutdown (PHP_RSHUTDOWN_FUNCTION) code respectively.
</p>

<H2><a name="Php_nn3">32.3 Cross language polymorphism</a></H2>


<p>
Proxy classes provide a more natural, object-oriented way to access
extension classes. As described above, each proxy instance has an
associated C++ instance, and method calls to the proxy are passed to the
C++ instance transparently.
</p>

<p>
This arrangement is asymmetric in the sense that no corresponding
mechanism exists to pass method calls down the inheritance chain from
C++ to PHP. In particular, if a C++ class has been extended in PHP
(by extending the proxy class), these extensions will not be visible
from C++ code. Virtual method calls from C++ are thus not able access
the lowest implementation in the inheritance chain.
</p>

<p>
Changes have been made to SWIG 1.3.18 to address this problem and make
the relationship between C++ classes and proxy classes more symmetric.
To achieve this goal, new classes called directors are introduced at the
bottom of the C++ inheritance chain. Support for generating PHP classes
has been added in SWIG 1.3.40. The job of the directors is to route
method calls correctly, either to C++ implementations higher in the
inheritance chain or to PHP implementations lower in the inheritance
chain. The upshot is that C++ classes can be extended in PHP and from
C++ these extensions look exactly like native C++ classes. Neither C++
code nor PHP code needs to know where a particular method is
implemented: the combination of proxy classes, director classes, and C
wrapper functions takes care of all the cross-language method routing
transparently.
</p>

<H3><a name="Php_nn3_1">32.3.1 Enabling directors</a></H3>


<p>
The director feature is disabled by default.  To use directors you
must make two changes to the interface file.  First, add the "directors"
option to the %module directive, like this:
</p>

<div class="code">
<pre>
%module(directors="1") modulename
</pre>
</div>

<p>
Without this option no director code will be generated.  Second, you
must use the %feature("director") directive to tell SWIG which classes 
and methods should get directors.  The %feature directive can be applied 
globally, to specific classes, and to specific methods, like this:
</p>

<div class="code">
<pre>
// generate directors for all classes that have virtual methods
%feature("director");         

// generate directors for the virtual methods in class Foo
%feature("director") Foo;      
</pre>
</div>

<p>
You can use the %feature("nodirector") directive to turn off
directors for specific classes or methods.  So for example,
</p>

<div class="code">
<pre>
%feature("director") Foo;
%feature("nodirector") Foo::bar;
</pre>
</div>

<p>
will generate directors for the virtual methods of class Foo except
bar().  
</p>

<p>
Directors can also be generated implicitly through inheritance. 
In the following, class Bar will get a director class that handles
the methods one() and two() (but not three()):
</p>

<div class="code">
<pre>
%feature("director") Foo;
class Foo {
public:
  Foo(int foo);
  virtual void one();
  virtual void two();
};

class Bar: public Foo {
public:
  virtual void three();
};
</pre>
</div>

<p>
then at the PHP side you can define
</p>

<div class="targetlang">
<pre>
class MyFoo extends Foo {
  function one() {
    print "one from php\n";
  }
}
</pre>
</div>


<H3><a name="Php_nn3_2">32.3.2 Director classes</a></H3>


 


<p>
For each class that has directors enabled, SWIG generates a new class
that derives from both the class in question and a special
<tt>Swig::Director</tt> class. These new classes, referred to as director
classes, can be loosely thought of as the C++ equivalent of the PHP
proxy classes. The director classes store a pointer to their underlying
PHP object.  Indeed, this is quite similar to <tt>struct swig_object_wrapper</tt>
which is used to implement the PHP proxy classes.
</p>

<p>
For simplicity let's ignore the <tt>Swig::Director</tt> class and refer to the
original C++ class as the director's base class. By default, a director
class extends all virtual methods in the inheritance chain of its base
class (see the preceding section for how to modify this behavior).
Virtual methods that have a final specifier are unsurprisingly excluded.
Thus the virtual method calls, whether they originate in C++ or in
PHP via proxy classes, eventually end up in at the implementation in the
director class. The job of the director methods is to route these method
calls to the appropriate place in the inheritance chain. By "appropriate
place" we mean the method that would have been called if the C++ base
class and its extensions in PHP were seamlessly integrated. That
seamless integration is exactly what the director classes provide,
transparently skipping over all the messy extension API glue that binds
the two languages together.
</p>

<p>
In reality, the "appropriate place" is one of only two possibilities:
C++ or PHP. Once this decision is made, the rest is fairly easy. If the
correct implementation is in C++, then the lowest implementation of the
method in the C++ inheritance chain is called explicitly. If the correct
implementation is in PHP, the Zend API is used to call the method of the
underlying PHP object (after which the usual virtual method resolution
in PHP automatically finds the right implementation).
</p>

<p>
Now how does the director decide which language should handle the method call?
The basic rule is to handle the method in PHP, unless there's a good
reason not to. The reason for this is simple: PHP has the most
"extended" implementation of the method. This assertion is guaranteed,
since at a minimum the PHP proxy class implements the method. If the
method in question has been extended by a class derived from the proxy
class, that extended implementation will execute exactly as it should.
If not, the proxy class will route the method call into a C wrapper
function, expecting that the method will be resolved in C++. The wrapper
will call the virtual method of the C++ instance, and since the director
extends this the call will end up right back in the director method. Now
comes the "good reason not to" part. If the director method were to blindly
call the PHP method again, it would get stuck in an infinite loop. We avoid this
situation by adding special code to the C wrapper function that tells
the director method to not do this.  The C wrapper function compares the
called and the declaring class name of the given method.  If these are
not the same, then the C wrapper function tells the director to resolve
the method by calling up the C++ inheritance chain, preventing an
infinite loop.
</p>

<p>
One more point needs to be made about the relationship between director
classes and proxy classes. When a proxy class instance is created in
PHP, SWIG creates an instance of the original C++ class and stores it
in the <tt>struct swig_object_wrapper</tt>. This is true whether or not
directors are enabled for the particular class in question. However
when a class <i>derived</i> from a proxy class is created, SWIG instead
creates an instance of the corresponding C++ director class.
The reason for this difference is that user-defined subclasses
may override or extend methods of the original class, so the director
class is needed to route calls to these methods correctly. For
unmodified proxy classes, all methods are ultimately implemented in C++
so there is no need for the extra overhead involved with routing the
calls through PHP.
</p>

<H3><a name="Php_nn3_3">32.3.3 Ownership and object destruction</a></H3>


<p>
Memory management issues are slightly more complicated with directors
than for proxy classes alone. PHP instances hold a pointer to the
associated C++ director object, and the director in turn holds a pointer
back to the PHP object. By default, proxy classes own their C++ director
object and take care of deleting it when they are garbage collected.
</p>

<p>
This relationship can be reversed by calling the special
<tt>-&gt;thisown</tt> property of the proxy class. After setting this
property to <tt>0</tt>, the director class no longer destroys the PHP
object.  Assuming no outstanding references to the PHP object remain,
the PHP object will be destroyed at the same time. This is a good thing,
since directors and proxies refer to each other and so must be created
and destroyed together. Destroying one without destroying the other will
likely cause your program to segfault.
</p>

<p>
Here is an example:
</p>

<div class="code">
<pre>
class Foo {
public:
  ...
};
class FooContainer {
public:
  void addFoo(Foo *);
  ...
};
</pre>
</div>

<br>

<div class="targetlang">
<pre>
$c = new FooContainer();
$a = new Foo();
$a-&gt;thisown = 0;
$c-&gt;addFoo($a);
</pre>
</div>

<p>
In this example, we are assuming that FooContainer will take care of
deleting all the Foo pointers it contains at some point.
</p>

<H3><a name="Php_nn3_4">32.3.4 Exception unrolling</a></H3>


<p>
With directors routing method calls to PHP, and proxies routing them
to C++, the handling of exceptions is an important concern. By default, an
exception thrown in PHP code called from C++ causes the PHP interpreter
to flag that an exception is thrown, then return passes to C++ as if
the PHP function had returned <code>Null</code>.  Assuming the directorout
typemaps handle this (those SWIG defines by default should) then once
control returns to PHP code again, the PHP exception will actually propagate.
</p>

<p>
Sometimes this control flow is problematic, and you want to skip any
handling in the C++ code.  To achieve this, it is necessary
to temporarily translate the PHP exception into a C++ exception. This can be
achieved using the %feature("director:except") directive. The following code
should suffice in most cases:
</p>

<div class="code">
<pre>
%feature("director:except") {
#if SWIG_VERSION &gt;= 0x040100
  if ($error != NULL)
#else
  if ($error == FAILURE)
#endif
  {
    throw Swig::DirectorMethodException();
  }
}
</pre>
</div>

<p>
If you only need to support SWIG &gt;= 4.1.0, you can just use the
<tt>($error != NULL)</tt> condition.
</p>

<p>
In SWIG 4.1.0, <tt>$error</tt> was changed in the SWIG/PHP director
implementation to make it work more like how it does for other languages.
Previously, <tt>$error</tt> didn't actually indicate an exception, but instead
was only set to <tt>FAILURE</tt> if there was a problem calling the PHP method.
Now <tt>$error</tt> indicates if the PHP method threw a PHP exception, and
directorout typemaps for PHP no longer need to be gated by <tt>if (EG(exception))</tt>.
</p>

<p>
This code will check the PHP error state after each method call from a
director into PHP, and throw a C++ exception if an error occurred.  This
exception can be caught in C++ to implement an error handler.
Currently no information about the PHP error is stored in the
Swig::DirectorMethodException object, but this will likely change in the
future.
</p>

<p>
It may be the case that a method call originates in PHP, travels up to
C++ through a proxy class, and then back into PHP via a director method.
If an exception occurs in PHP at this point, it would be nice for that
exception to find its way back to the original caller. This can be done
by combining a normal %exception directive with the
<tt>director:except</tt> handler shown above. Here is an example of a
suitable exception handler:
</p>

<div class="code">
<pre>
%exception {
  try { $action }
  catch (Swig::DirectorException &amp;e) { SWIG_fail; }
}
</pre>
</div>

<p>
The class Swig::DirectorException used in this example is actually a
base class of Swig::DirectorMethodException, so it will trap this
exception. Because the PHP error state is still set when
Swig::DirectorMethodException is thrown, PHP will register the exception
as soon as the C wrapper function returns.
</p>

<H3><a name="Php_nn3_5">32.3.5 Overhead and code bloat</a></H3>


<p>
Enabling directors for a class will generate a new director method for
every virtual method in the class' inheritance chain. This alone can
generate a lot of code bloat for large hierarchies. Method arguments
that require complex conversions to and from target language types can
result in large director methods. For this reason it is recommended that
you selectively enable directors only for specific classes that are
likely to be extended in PHP and used in C++.
</p>

<p>
Compared to classes that do not use directors, the call routing in the
director methods does add some overhead. In particular, at least one
dynamic cast and one extra function call occurs per method call from
PHP. Relative to the speed of PHP execution this is probably completely
negligible. For worst case routing, a method call that ultimately
resolves in C++ may take one extra detour through PHP in order to ensure
that the method does not have an extended PHP implementation. This could
result in a noticeable overhead in some cases.
</p>

<p>
Although directors make it natural to mix native C++ objects with PHP
objects (as director objects) via a common base class pointer, one
should be aware of the obvious fact that method calls to PHP objects
will be much slower than calls to C++ objects. This situation can be
optimized by selectively enabling director methods (using the %feature
directive) for only those methods that are likely to be extended in PHP.
</p>

<H3><a name="Php_nn3_6">32.3.6 Typemaps</a></H3>


<p>
Typemaps for input and output of most of the basic types from director
classes have been written. These are roughly the reverse of the usual
input and output typemaps used by the wrapper code. The typemap
operation names are 'directorin', 'directorout', and 'directorargout'.
The director code does not currently use any of the other kinds of
typemaps.  It is not clear at this point which kinds are appropriate and
need to be supported.
</p>


<H3><a name="Php_nn3_7">32.3.7 Miscellaneous</a></H3>


<p> Director typemaps for STL classes are mostly in place, and hence you
should be able to use std::string, etc., as you would any other type.
</p>

</body>
</html>