-
Notifications
You must be signed in to change notification settings - Fork 720
/
namespaces.xml
1564 lines (1465 loc) · 47.7 KB
/
namespaces.xml
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
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<chapter xml:id="language.namespaces" xmlns="http://docbook.org/ns/docbook"
version="1.1">
<title>Namespaces</title>
<sect1 xml:id="language.namespaces.rationale">
<title>Namespaces overview</title>
<titleabbrev>Overview</titleabbrev>
<?phpdoc print-version-for="namespaces"?>
<simpara>
What are namespaces? In the broadest definition namespaces are a way of encapsulating
items. This can be seen as an abstract concept in many places. For example, in any
operating system directories serve to group related files, and act as a namespace for
the files within them. As a concrete example, the file <literal>foo.txt</literal> can
exist in both directory <literal>/home/greg</literal> and in <literal>/home/other</literal>,
but two copies of <literal>foo.txt</literal> cannot co-exist in the same directory. In
addition, to access the <literal>foo.txt</literal> file outside of the
<literal>/home/greg</literal> directory, we must prepend the directory name to the file
name using the directory separator to get <literal>/home/greg/foo.txt</literal>. This
same principle extends to namespaces in the programming world.
</simpara>
<simpara>
In the PHP world, namespaces are designed to solve two problems that authors
of libraries and applications encounter when creating re-usable code elements
such as classes or functions:
</simpara>
<para>
<orderedlist>
<listitem>
<simpara>
Name collisions between code you create, and
internal PHP classes/functions/constants or third-party classes/functions/constants.
</simpara>
</listitem>
<listitem>
<simpara>
Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem,
improving readability of source code.
</simpara>
</listitem>
</orderedlist>
</para>
<simpara>
PHP Namespaces provide a way in which to group related classes, interfaces,
functions and constants. Here is an example of namespace syntax in PHP:
</simpara>
<example>
<title>Namespace syntax example</title>
<programlisting role="php">
<![CDATA[
<?php
namespace my\name; // see "Defining Namespaces" section
class MyClass {}
function myfunction() {}
const MYCONST = 1;
$a = new MyClass;
$c = new \my\name\MyClass; // see "Global Space" section
$a = strlen('hi'); // see "Using namespaces: fallback to global
// function/constant" section
$d = namespace\MYCONST; // see "namespace operator and __NAMESPACE__
// constant" section
$d = __NAMESPACE__ . '\MYCONST';
echo constant($d); // see "Namespaces and dynamic language features" section
?>
]]>
</programlisting>
</example>
<note>
<simpara>
Namespace names are case-insensitive.
</simpara>
</note>
<note>
<para>
The Namespace name <literal>PHP</literal>, and compound names starting
with this name (like <literal>PHP\Classes</literal>) are reserved for internal language use
and should not be used in the userspace code.
</para>
</note>
</sect1>
<sect1 xml:id="language.namespaces.definition">
<title>Defining namespaces</title>
<titleabbrev>Namespaces</titleabbrev>
<?phpdoc print-version-for="namespaces"?>
<para>
Although any valid PHP code can be contained within a namespace, only the following
types of code are affected by namespaces: classes (including abstracts and traits), interfaces, functions and constants.
</para>
<para>
Namespaces are declared using the <literal>namespace</literal>
keyword. A file containing a namespace must declare the namespace
at the top of the file before any other code - with one exception: the
<xref linkend="control-structures.declare" /> keyword.
<example>
<title>Declaring a single namespace</title>
<programlisting role="php">
<![CDATA[
<?php
namespace MyProject;
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
?>
]]>
</programlisting>
</example>
<note>
<simpara>
Fully qualified names (i.e. names starting with a backslash) are not allowed in namespace
declarations, because such constructs are interpreted as relative namespace expressions.
</simpara>
</note>
The only code construct allowed before a namespace declaration is the
<literal>declare</literal> statement, for defining encoding of a source file. In addition,
no non-PHP code may precede a namespace declaration, including extra whitespace:
<example>
<title>Declaring a single namespace</title>
<programlisting role="php">
<![CDATA[
<html>
<?php
namespace MyProject; // fatal error - namespace must be the first statement in the script
?>
]]>
</programlisting>
</example>
</para>
<para>
In addition, unlike any other PHP construct, the same namespace may be defined
in multiple files, allowing splitting up of a namespace's contents across the filesystem.
</para>
</sect1>
<sect1 xml:id="language.namespaces.nested">
<title>Declaring sub-namespaces</title>
<titleabbrev>Sub-namespaces</titleabbrev>
<?phpdoc print-version-for="namespaces"?>
<para>
Much like directories and files, PHP namespaces also contain the ability to specify
a hierarchy of namespace names. Thus, a namespace name can be defined with
sub-levels:
<example>
<title>Declaring a single namespace with hierarchy</title>
<programlisting role="php">
<![CDATA[
<?php
namespace MyProject\Sub\Level;
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
?>
]]>
</programlisting>
</example>
The above example creates constant <literal>MyProject\Sub\Level\CONNECT_OK</literal>,
class <literal>MyProject\Sub\Level\Connection</literal> and function
<literal>MyProject\Sub\Level\connect</literal>.
</para>
</sect1>
<sect1 xml:id="language.namespaces.definitionmultiple">
<title>Defining multiple namespaces in the same file</title>
<titleabbrev>Defining multiple namespaces in the same file</titleabbrev>
<?phpdoc print-version-for="namespaces"?>
<para>
Multiple namespaces may also be declared in the same file. There are two allowed
syntaxes.
</para>
<para>
<example>
<title>Declaring multiple namespaces, simple combination syntax</title>
<programlisting role="php">
<![CDATA[
<?php
namespace MyProject;
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
namespace AnotherProject;
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
?>
]]>
</programlisting>
</example>
</para>
<para>
This syntax is not recommended for combining namespaces into a single file.
Instead it is recommended to use the alternate bracketed syntax.
</para>
<para>
<example>
<title>Declaring multiple namespaces, bracketed syntax</title>
<programlisting role="php">
<![CDATA[
<?php
namespace MyProject {
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}
namespace AnotherProject {
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}
?>
]]>
</programlisting>
</example>
</para>
<para>
It is strongly discouraged as a coding practice to combine multiple namespaces into
the same file. The primary use case is to combine multiple PHP scripts into the same
file.
</para>
<para>
To combine global non-namespaced code with namespaced code, only bracketed syntax is
supported. Global code should be
encased in a namespace statement with no namespace name as in:
<example>
<title>Declaring multiple namespaces and unnamespaced code</title>
<programlisting role="php">
<![CDATA[
<?php
namespace MyProject {
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}
namespace { // global code
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>
]]>
</programlisting>
</example>
</para>
<para>
No PHP code may exist outside of the namespace brackets except for an opening
declare statement.
<example>
<title>Declaring multiple namespaces and unnamespaced code</title>
<programlisting role="php">
<![CDATA[
<?php
declare(encoding='UTF-8');
namespace MyProject {
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}
namespace { // global code
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>
]]>
</programlisting>
</example>
</para>
</sect1>
<sect1 xml:id="language.namespaces.basics">
<title>Using namespaces: Basics</title>
<titleabbrev>Basics</titleabbrev>
<?phpdoc print-version-for="namespaces"?>
<para>
Before discussing the use of namespaces, it is important to understand how PHP
knows which namespaced element your code is requesting. A simple analogy can be made
between PHP namespaces and a filesystem. There are three ways to access a file in a
file system:
<orderedlist>
<listitem>
<simpara>
Relative file name like <literal>foo.txt</literal>. This resolves to
<literal>currentdirectory/foo.txt</literal> where <literal>currentdirectory</literal> is the
directory currently occupied. So if the current directory is
<literal>/home/foo</literal>, the name resolves to <literal>/home/foo/foo.txt</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
Relative path name like <literal>subdirectory/foo.txt</literal>. This resolves
to <literal>currentdirectory/subdirectory/foo.txt</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
Absolute path name like <literal>/main/foo.txt</literal>. This resolves
to <literal>/main/foo.txt</literal>.
</simpara>
</listitem>
</orderedlist>
The same principle can be applied to namespaced elements in PHP. For
example, a class name can be referred to in three ways:
<orderedlist>
<listitem>
<simpara>
Unqualified name, or an unprefixed class name like
<literal>$a = new foo();</literal> or
<literal>foo::staticmethod();</literal>. If the current namespace is
<literal>currentnamespace</literal>, this resolves to
<literal>currentnamespace\foo</literal>. If
the code is global, non-namespaced code, this resolves to <literal>foo</literal>.
</simpara>
<simpara>
One caveat: unqualified names for functions and constants will
resolve to global functions and constants if the namespaced function or constant
is not defined. See <link linkend="language.namespaces.fallback">Using namespaces:
fallback to global function/constant</link> for details.
</simpara>
</listitem>
<listitem>
<simpara>
Qualified name, or a prefixed class name like
<literal>$a = new subnamespace\foo();</literal> or
<literal>subnamespace\foo::staticmethod();</literal>. If the current namespace is
<literal>currentnamespace</literal>, this resolves to
<literal>currentnamespace\subnamespace\foo</literal>. If
the code is global, non-namespaced code, this resolves to <literal>subnamespace\foo</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
Fully qualified name, or a prefixed name with global prefix operator like
<literal>$a = new \currentnamespace\foo();</literal> or
<literal>\currentnamespace\foo::staticmethod();</literal>. This always resolves
to the literal name specified in the code, <literal>currentnamespace\foo</literal>.
</simpara>
</listitem>
</orderedlist>
</para>
<para>
Here is an example of the three kinds of syntax in actual code:
<informalexample>
<simpara>file1.php</simpara>
<programlisting role="php">
<![CDATA[
<?php
namespace Foo\Bar\subnamespace;
const FOO = 1;
function foo() {}
class foo
{
static function staticmethod() {}
}
?>
]]>
</programlisting>
<simpara>file2.php</simpara>
<programlisting role="php">
<![CDATA[
<?php
namespace Foo\Bar;
include 'file1.php';
const FOO = 2;
function foo() {}
class foo
{
static function staticmethod() {}
}
/* Unqualified name */
foo(); // resolves to function Foo\Bar\foo
foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo FOO; // resolves to constant Foo\Bar\FOO
/* Qualified name */
subnamespace\foo(); // resolves to function Foo\Bar\subnamespace\foo
subnamespace\foo::staticmethod(); // resolves to class Foo\Bar\subnamespace\foo,
// method staticmethod
echo subnamespace\FOO; // resolves to constant Foo\Bar\subnamespace\FOO
/* Fully qualified name */
\Foo\Bar\foo(); // resolves to function Foo\Bar\foo
\Foo\Bar\foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo \Foo\Bar\FOO; // resolves to constant Foo\Bar\FOO
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
Note that to access any global
class, function or constant, a fully qualified name can be used, such as
<function>\strlen</function> or <classname>\Exception</classname> or
\<constant>INI_ALL</constant>.
<example>
<title>Accessing global classes, functions and constants from within a namespace</title>
<programlisting role="php">
<![CDATA[
<?php
namespace Foo;
function strlen() {}
const INI_ALL = 3;
class Exception {}
$a = \strlen('hi'); // calls global function strlen
$b = \INI_ALL; // accesses global constant INI_ALL
$c = new \Exception('error'); // instantiates global class Exception
?>
]]>
</programlisting>
</example>
</para>
</sect1>
<sect1 xml:id="language.namespaces.dynamic">
<title>Namespaces and dynamic language features</title>
<titleabbrev>Namespaces and dynamic language features</titleabbrev>
<?phpdoc print-version-for="namespaces"?>
<para>
PHP's implementation of namespaces is influenced by its dynamic nature as a programming
language. Thus, to convert code like the following example into namespaced code:
<example>
<title>Dynamically accessing elements</title>
<simpara>example1.php:</simpara>
<programlisting role="php">
<![CDATA[
<?php
class classname
{
function __construct()
{
echo __METHOD__,"\n";
}
}
function funcname()
{
echo __FUNCTION__,"\n";
}
const constname = "global";
$a = 'classname';
$obj = new $a; // prints classname::__construct
$b = 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"; // prints global
?>
]]>
</programlisting>
</example>
One must use the fully qualified name (class name with namespace prefix).
Note that because there is no difference between a qualified and a fully qualified Name
inside a dynamic class name, function name, or constant name, the leading backslash is
not necessary.
<example>
<title>Dynamically accessing namespaced elements</title>
<programlisting role="php">
<![CDATA[
<?php
namespace namespacename;
class classname
{
function __construct()
{
echo __METHOD__,"\n";
}
}
function funcname()
{
echo __FUNCTION__,"\n";
}
const constname = "namespaced";
/* note that if using double quotes, "\\namespacename\\classname" must be used */
$a = '\namespacename\classname';
$obj = new $a; // prints namespacename\classname::__construct
$a = 'namespacename\classname';
$obj = new $a; // also prints namespacename\classname::__construct
$b = 'namespacename\funcname';
$b(); // prints namespacename\funcname
$b = '\namespacename\funcname';
$b(); // also prints namespacename\funcname
echo constant('\namespacename\constname'), "\n"; // prints namespaced
echo constant('namespacename\constname'), "\n"; // also prints namespaced
?>
]]>
</programlisting>
</example>
</para>
<para>
Be sure to read the <link linkend="language.namespaces.faq.quote">note about
escaping namespace names in strings</link>.
</para>
</sect1>
<sect1 xml:id="language.namespaces.nsconstants">
<title>The namespace keyword and __NAMESPACE__ magic constant</title>
<titleabbrev>namespace keyword and __NAMESPACE__</titleabbrev>
<?phpdoc print-version-for="namespaces"?>
<para>
PHP supports two ways of abstractly accessing elements within the current namespace,
the <constant>__NAMESPACE__</constant> magic constant, and the <literal>namespace</literal>
keyword.
</para>
<para>
The value of <constant>__NAMESPACE__</constant> is a string that contains the current
namespace name. In global, un-namespaced code, it contains an empty string.
<example>
<title>__NAMESPACE__ example, namespaced code</title>
<programlisting role="php">
<![CDATA[
<?php
namespace MyProject;
echo '"', __NAMESPACE__, '"'; // outputs "MyProject"
?>
]]>
</programlisting>
</example>
<example>
<title>__NAMESPACE__ example, global code</title>
<programlisting role="php">
<![CDATA[
<?php
echo '"', __NAMESPACE__, '"'; // outputs ""
?>
]]>
</programlisting>
</example>
The <constant>__NAMESPACE__</constant> constant is useful for dynamically constructing
names, for instance:
<example>
<title>using __NAMESPACE__ for dynamic name construction</title>
<programlisting role="php">
<![CDATA[
<?php
namespace MyProject;
function get($classname)
{
$a = __NAMESPACE__ . '\\' . $classname;
return new $a;
}
?>
]]>
</programlisting>
</example>
</para>
<para>
The <literal>namespace</literal> keyword can be used to explicitly request
an element from the current namespace or a sub-namespace. It is the namespace
equivalent of the <literal>self</literal> operator for classes.
<example>
<title>the namespace operator, inside a namespace</title>
<programlisting role="php">
<![CDATA[
<?php
namespace MyProject;
use blah\blah as mine; // see "Using namespaces: Aliasing/Importing"
blah\mine(); // calls function MyProject\blah\mine()
namespace\blah\mine(); // calls function MyProject\blah\mine()
namespace\func(); // calls function MyProject\func()
namespace\sub\func(); // calls function MyProject\sub\func()
namespace\cname::method(); // calls static method "method" of class MyProject\cname
$a = new namespace\sub\cname(); // instantiates object of class MyProject\sub\cname
$b = namespace\CONSTANT; // assigns value of constant MyProject\CONSTANT to $b
?>
]]>
</programlisting>
</example>
<example>
<title>the namespace operator, in global code</title>
<programlisting role="php">
<![CDATA[
<?php
namespace\func(); // calls function func()
namespace\sub\func(); // calls function sub\func()
namespace\cname::method(); // calls static method "method" of class cname
$a = new namespace\sub\cname(); // instantiates object of class sub\cname
$b = namespace\CONSTANT; // assigns value of constant CONSTANT to $b
?>
]]>
</programlisting>
</example>
</para>
</sect1>
<sect1 xml:id="language.namespaces.importing">
<title>Using namespaces: Aliasing/Importing</title>
<titleabbrev>Aliasing and Importing</titleabbrev>
<?phpdoc print-version-for="namespaces"?>
<para>
The ability to refer to an external fully qualified name with an alias, or importing,
is an important feature of namespaces. This is similar to the
ability of unix-based filesystems to create symbolic links to a file or to a directory.
</para>
<para>
PHP can alias(/import) constants, functions, classes, interfaces, traits, enums and namespaces.
</para>
<para>
Aliasing is accomplished with the <literal>use</literal> operator.
Here is an example showing all 5 kinds of importing:
<example>
<title>importing/aliasing with the use operator</title>
<programlisting role="php">
<![CDATA[
<?php
namespace foo;
use My\Full\Classname as Another;
// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;
// importing a global class
use ArrayObject;
// importing a function
use function My\Full\functionName;
// aliasing a function
use function My\Full\functionName as func;
// importing a constant
use const My\Full\CONSTANT;
$obj = new namespace\Another; // instantiates object of class foo\Another
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the "use ArrayObject" we would instantiate an object of class foo\ArrayObject
func(); // calls function My\Full\functionName
echo CONSTANT; // echoes the value of My\Full\CONSTANT
?>
]]>
</programlisting>
</example>
Note that for namespaced names (fully qualified namespace names containing
namespace separator, such as <literal>Foo\Bar</literal> as opposed to global names that
do not, such as <literal>FooBar</literal>), the leading backslash is unnecessary and not
recommended, as import names
must be fully qualified, and are not processed relative to the current namespace.
</para>
<para>
PHP additionally supports a convenience shortcut to place multiple use statements
on the same line
<example>
<title>importing/aliasing with the use operator, multiple use statements combined</title>
<programlisting role="php">
<![CDATA[
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
?>
]]>
</programlisting>
</example>
</para>
<para>
Importing is performed at compile-time, and so does not affect dynamic class, function
or constant names.
<example>
<title>Importing and dynamic names</title>
<programlisting role="php">
<![CDATA[
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
$a = 'Another';
$obj = new $a; // instantiates object of class Another
?>
]]>
</programlisting>
</example>
</para>
<para>
In addition, importing only affects unqualified and qualified names. Fully qualified
names are absolute, and unaffected by imports.
<example>
<title>Importing and fully qualified names</title>
<programlisting role="php">
<![CDATA[
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
$obj = new \Another; // instantiates object of class Another
$obj = new Another\thing; // instantiates object of class My\Full\Classname\thing
$obj = new \Another\thing; // instantiates object of class Another\thing
?>
]]>
</programlisting>
</example>
</para>
<sect2 xml:id="language.namespaces.importing.scope">
<title>Scoping rules for importing</title>
<para>
The <literal>use</literal> keyword must be declared in the
outermost scope of a file (the global scope) or inside namespace
declarations. This is because the importing is done at compile
time and not runtime, so it cannot be block scoped. The following
example will show an illegal use of the <literal>use</literal>
keyword:
</para>
<para>
<example>
<title>Illegal importing rule</title>
<programlisting role="php">
<![CDATA[
<?php
namespace Languages;
function toGreenlandic()
{
use Languages\Danish;
// ...
}
?>
]]>
</programlisting>
</example>
</para>
<note>
<para>
Importing rules are per file basis, meaning included files will
<emphasis>NOT</emphasis> inherit the parent file's importing rules.
</para>
</note>
</sect2>
<sect2 xml:id="language.namespaces.importing.group">
<title>Group <literal>use</literal> declarations</title>
<para>
Classes, functions and constants being imported from
the same &namespace; can be grouped together in a single &use.namespace;
statement.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;
use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;
use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;
// is equivalent to the following groupped use declaration
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};
]]>
</programlisting>
</informalexample>
</sect2>
</sect1>
<sect1 xml:id="language.namespaces.global">
<title>Global space</title>
<titleabbrev>Global space</titleabbrev>
<?phpdoc print-version-for="namespaces"?>
<para>
Without any namespace definition, all class and function definitions are
placed into the global space - as it was in PHP before namespaces were
supported. Prefixing a name with <literal>\</literal> will specify that
the name is required from the global space even in the context of the
namespace.
<example>
<title>Using global space specification</title>
<programlisting role="php">
<![CDATA[
<?php
namespace A\B\C;
/* This function is A\B\C\fopen */
function fopen() {
/* ... */
$f = \fopen(...); // call global fopen
return $f;
}
?>
]]>
</programlisting>
</example>
</para>
</sect1>
<sect1 xml:id="language.namespaces.fallback">
<title>Using namespaces: fallback to the global space for functions and constants</title>
<titleabbrev>Fallback to global space</titleabbrev>
<?phpdoc print-version-for="namespaces"?>
<para>
Inside a namespace, when PHP encounters an unqualified Name in a class name, function or
constant context, it resolves these with different priorities. Class names always
resolve to the current namespace name. Thus to access internal or non-namespaced
user classes, one must refer to them with their fully qualified Name as in:
<example>
<title>Accessing global classes inside a namespace</title>
<programlisting role="php">
<![CDATA[
<?php
namespace A\B\C;
class Exception extends \Exception {}
$a = new Exception('hi'); // $a is an object of class A\B\C\Exception
$b = new \Exception('hi'); // $b is an object of class Exception
$c = new ArrayObject; // fatal error, class A\B\C\ArrayObject not found
?>
]]>
</programlisting>
</example>
</para>
<para>
For functions and constants, PHP will fall back to global functions or constants
if a namespaced function or constant does not exist.
<example>
<title>global functions/constants fallback inside a namespace</title>
<programlisting role="php">
<![CDATA[
<?php
namespace A\B\C;
const E_ERROR = 45;
function strlen($str)
{
return \strlen($str) - 1;
}
echo E_ERROR, "\n"; // prints "45"
echo INI_ALL, "\n"; // prints "7" - falls back to global INI_ALL
echo strlen('hi'), "\n"; // prints "1"
if (is_array('hi')) { // prints "is not array"
echo "is array\n";
} else {
echo "is not array\n";
}
?>
]]>
</programlisting>
</example>
</para>
</sect1>
<sect1 xml:id="language.namespaces.rules">
<title>Name resolution rules</title>
<titleabbrev>Name resolution rules</titleabbrev>
<?phpdoc print-version-for="namespaces"?>
<para>
For the purposes of these resolution rules, here are some important definitions:
<variablelist>
<title>Namespace name definitions</title>
<varlistentry>
<term>Unqualified name</term>
<listitem>
<para>
This is an identifier without a namespace separator, such as <literal>Foo</literal>
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>Qualified name</term>
<listitem>
<para>
This is an identifier with a namespace separator, such as <literal>Foo\Bar</literal>
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>Fully qualified name</term>
<listitem>
<para>
This is an identifier with a namespace separator that begins with a
namespace separator, such as <literal>\Foo\Bar</literal>. The namespace
<literal>\Foo</literal> is also a fully qualified name.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>Relative name</term>
<listitem>
<para>
This is an identifier starting with <literal>namespace</literal>, such as
<literal>namespace\Foo\Bar</literal>.
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
<para>
Names are resolved following these resolution rules:
<orderedlist>
<listitem>
<simpara>
Fully qualified names always resolve to the name without leading namespace separator.
For instance <literal>\A\B</literal> resolves to <literal>A\B</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
Relative names always resolve to the name with <literal>namespace</literal> replaced by
the current namespace. If the name occurs in the global namespace, the
<literal>namespace\</literal> prefix is stripped. For example <literal>namespace\A</literal>
inside namespace <literal>X\Y</literal> resolves to <literal>X\Y\A</literal>. The same name
inside the global namespace resolves to <literal>A</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
For qualified names the first segment of the name is translated according to the current
class/namespace import table. For example, if the namespace <literal>A\B\C</literal> is
imported as <literal>C</literal>, the name <literal>C\D\E</literal> is translated to
<literal>A\B\C\D\E</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
For qualified names, if no import rule applies, the current namespace is prepended to the
name. For example, the name <literal>C\D\E</literal> inside namespace <literal>A\B</literal>,
resolves to <literal>A\B\C\D\E</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
For unqualified names, the name is translated according to the current import table for the
respective symbol type. This means that class-like names are translated according to the
class/namespace import table, function names according to the function import table and
constants according to the constant import table. For example, after
<literal>use A\B\C;</literal> a usage such as <literal>new C()</literal> resolves to the name
<literal>A\B\C()</literal>. Similarly, after <literal>use function A\B\foo;</literal> a usage
such as <literal>foo()</literal> resolves to the name <literal>A\B\foo</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
For unqualified names, if no import rule applies and the name refers to a class-like symbol,
the current namespace is prepended. For example <literal>new C()</literal> inside namespace
<literal>A\B</literal> resolves to name <literal>A\B\C</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
For unqualified names, if no import rule applies and the name refers to a function or constant
and the code is outside the global namespace, the name is resolved at runtime.
Assuming the code is in namespace <literal>A\B</literal>, here is how a call to function
<literal>foo()</literal> is resolved:
</simpara>
<orderedlist>
<listitem>
<simpara>
It looks for a function from the current namespace:
<literal>A\B\foo()</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
It tries to find and call the <emphasis>global</emphasis> function
<literal>foo()</literal>.
</simpara>
</listitem>
</orderedlist>
</listitem>
</orderedlist>
</para>
<example>
<title>Name resolutions illustrated</title>
<programlisting role="php">
<![CDATA[
<?php
namespace A;
use B\D, C\E as F;