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
|
<?xml version="1.0" encoding="iso-8859-1"?>
<chapter id="language.variables">
<title>Variables</title>
<sect1 id="language.variables.basics">
<title>Basics</title>
<simpara>
As variveis no PHP so representadas por um cifro($) seguido pelo
nome da varivel. Os nomes de varivel no PHP fazem distino entre
maisculas e minsculas.
Variables in PHP are represented by a dollar sign followed by the
name of the variable. The variable name is case-sensitive.
</simpara>
<para>
Os nomes de varivel seguem as mesmas regras como outros rtulos no PHP.
Um nome de varivel vlido se inicia com uma letra ou sublinhado, seguido
de qualquer nmero de letras, algarismos ou sublinhados. Em uma
expresso regular isto poderia ser representado desta forma:
'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
</para>
<note>
<simpara>
Para nosso propsito aqui, letras so a-z, A-Z e os caracteres
ASCII de 127 a 255 (0x7f-0xff).
</simpara>
</note>
<para>
<informalexample>
<programlisting role="php">
$var = "Bob";
$Var = "Joe";
echo "$var, $Var"; // imprime "Bob, Joe"
$4site = 'not yet'; // invlido; comea com algarismo
$_4site = 'not yet'; // vlido; comea com sublinhado
$tyte = 'mansikka'; // vlido; '' ASCII 228.
</programlisting>
</informalexample>
</para>
<para>
No PHP 3 as variveis so sempre atribudas por valor. Isto significa
dizer que quando voc atribui uma expresso a uma varivel, o valor
da expresso original copiado integralmente para a varivel de destino.
Isto significa que, aps atribuir o valor de uma varivel a
outra, a alterao de uma destas variveis no afetar a outra.
Para mairoes informaes sobre este tipo de atribuio, veja <link
linkend="language.expressions">Expresses</link>.
</para>
<para>
PHP 4 oferece um outro meio de atribuir valores a variveis:
<emphasis>atribuio por referncia</emphasis>. Isto significa que
a nova varivel simplesmente referencia (em outras palavras, "torna-se
um apelido para" ou "aponta para") a varivel original. Alteraes na
nova varivel afetam a original e vice versa. Isto significa tambm que
nenhuma cpia realizada, de modo que a atribuio ocorre mais rapidamente.
Entretanto, qualquer aumento de velocidade s ser realmente notado
em *loops* complexos ou em atribuies de grandes matrizes (*arrays*) ou objetos.
</para>
<para>
Para atribuir por referncia, simplesmente adicione um e-comercial (&)
na frente do nome da varivel que estiver sendo atribuda (varivel de origem)
Por exemplo, o trecho de cdigo abaixo imprime 'My name is Bob' duas vezes:
<informalexample>
<programlisting role="php">
<?php
$foo = 'Bob'; // Atribui o valor 'Bob' a varivel $foo
$bar = &$foo; // Referecia $foo atravs de $bar.
$bar = "My name is $bar"; // Altera $bar...
echo $foo; // $foo alterada tambm.
echo $bar;
?>
</programlisting>
</informalexample>
</para>
<para>
Uma observao importante a se fazer que somente variveis
nomeadas podem ser atribudas por referncia.
<informalexample>
<programlisting role="php">
<?php
$foo = 25;
$bar = &$foo; // Esta atribuio vlida.
$bar = &(24 * 7); // Invlido; referencia uma expresso sem nome.
function test() {
return 25;
}
$bar = &test(); // Invlido.
?>
</programlisting>
</informalexample>
</para>
</sect1>
<sect1 id="language.variables.predefined">
<title>Variveis Predefinidas</title>
<simpara>
PHP oferece um grande nmero de variveis predefinidas para qualquer
script que ele execute. Muitas destas variveis, entretanto, no podem
ser completamente documentadas uma vez dependem de diversos fatores como
o servidor no qual scripts so executados, a verso e configurao deste
servidor, dentre outros fatores. Algumas destas variveis no estaro
disponveis quando o PHP for executado na linha de comando.
</simpara>
<simpara>
A despeito destes fatores, temos aqui uma lista de variveis predefinidas
disponveis sob uma instalao padro do PHP 3 executado como um mdulo
em uma instalao padro do <ulink url="&url.apache;">Apache</ulink> 1.3.6.
</simpara>
<simpara>
Para obter uma lista de todas as variveis predefinidas (e um monte de
outras informaes teis), veja (e use) <function>phpinfo</function>.
</simpara>
<note>
<simpara>
This list is neither exhaustive nor intended to be. It is simply
a guideline as to what sorts of predefined variables you can
expect to have access to in your script.
</simpara>
</note>
<sect2 id="language.variables.predefined.apache">
<title>Apache variables</title>
<simpara>
These variables are created by the <ulink
url="&url.apache;">Apache</ulink> webserver. If you are running
another webserver, there is no guarantee that it will provide the
same variables; it may omit some, or provide others not listed
here. That said, a large number of these variables are accounted
for in the <ulink url="&url.cgispec;">CGI 1.1
specification</ulink>, so you should be able to expect those.
</simpara>
<simpara>
Note that few, if any, of these will be available (or indeed have
any meaning) if running PHP on the command line.
</simpara>
<para>
<variablelist>
<varlistentry>
<term>GATEWAY_INTERFACE</term>
<listitem>
<simpara>
What revision of the CGI specification the server is using;
i.e. 'CGI/1.1'.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>SERVER_NAME</term>
<listitem>
<simpara>
The name of the server host under which the current script is
executing. If the script is running on a virtual host, this
will be the value defined for that virtual host.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>SERVER_SOFTWARE</term>
<listitem>
<simpara>
Server identification string, given in the headers when
responding to requests.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>SERVER_PROTOCOL</term>
<listitem>
<simpara>
Name and revision of the information protocol via which the
page was requested; i.e. 'HTTP/1.0';
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>REQUEST_METHOD</term>
<listitem>
<simpara>
Which request method was used to access the page; i.e. 'GET',
'HEAD', 'POST', 'PUT'.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>QUERY_STRING</term>
<listitem>
<simpara>
The query string, if any, via which the page was accessed.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>DOCUMENT_ROOT</term>
<listitem>
<simpara>
The document root directory under which the current script is
executing, as defined in the server's configuration file.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>HTTP_ACCEPT</term>
<listitem>
<simpara>
Contents of the <literal>Accept:</literal> header from the
current request, if there is one.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>HTTP_ACCEPT_CHARSET</term>
<listitem>
<simpara>
Contents of the <literal>Accept-Charset:</literal> header
from the current request, if there is one. Example:
'iso-8859-1,*,utf-8'.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>HTTP_ENCODING</term>
<listitem>
<simpara>
Contents of the <literal>Accept-Encoding:</literal> header
from the current request, if there is one. Example: 'gzip'.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>HTTP_ACCEPT_LANGUAGE</term>
<listitem>
<simpara>
Contents of the <literal>Accept-Language:</literal> header
from the current request, if there is one. Example: 'en'.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>HTTP_CONNECTION</term>
<listitem>
<simpara>
Contents of the <literal>Connection:</literal> header from
the current request, if there is one. Example: 'Keep-Alive'.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>HTTP_HOST</term>
<listitem>
<simpara>
Contents of the <literal>Host:</literal> header from the
current request, if there is one.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>HTTP_REFERER</term>
<listitem>
<simpara>
The address of the page (if any) which referred the browser
to the current page. This is set by the user's browser; not
all browsers will set this.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>HTTP_USER_AGENT</term>
<listitem>
<simpara>
Contents of the <literal>User_Agent:</literal> header from
the current request, if there is one. This is a string
denoting the browser software being used to view the current
page; i.e. <computeroutput>Mozilla/4.5 [en] (X11; U; Linux
2.2.9 i586)</computeroutput>. Among other things, you can use
this value with <function>get_browser</function> to tailor
your page's functionality to the capabilities of the user's
browser.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>REMOTE_ADDR</term>
<listitem>
<simpara>
The IP address from which the user is viewing the current
page.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>REMOTE_PORT</term>
<listitem>
<simpara>
The port being used on the user's machine to communicate with
the web server.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>SCRIPT_FILENAME</term>
<listitem>
<simpara>
The absolute pathname of the currently executing script.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>SERVER_ADMIN</term>
<listitem>
<simpara>
The value given to the SERVER_ADMIN (for Apache) directive in
the web server configuration file. If the script is running
on a virtual host, this will be the value defined for that
virtual host.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>SERVER_PORT</term>
<listitem>
<simpara>
The port on the server machine being used by the web server
for communication. For default setups, this will be '80';
using SSL, for instance, will change this to whatever your
defined secure HTTP port is.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>SERVER_SIGNATURE</term>
<listitem>
<simpara>
String containing the server version and virtual host name
which are added to server-generated pages, if enabled.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>PATH_TRANSLATED</term>
<listitem>
<simpara>
Filesystem- (not document root-) based path to the current
script, after the server has done any virtual-to-real
mapping.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>SCRIPT_NAME</term>
<listitem>
<simpara>
Contains the current script's path. This is useful for pages
which need to point to themselves.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>REQUEST_URI</term>
<listitem>
<simpara>
The URI which was given in order to access this page; for
instance, '/index.html'.
</simpara>
</listitem>
</varlistentry>
</variablelist>
</para>
</sect2>
<sect2 id="language.variables.predefined.environment">
<title>Environment variables</title>
<simpara>
These variables are imported into PHP's global namespace from the
environment under which the PHP parser is running. Many are
provided by the shell under which PHP is running and different
systems are likely running different kinds of shells, a
definitive list is impossible. Please see your shell's
documentation for a list of defined environment variables.
</simpara>
<simpara>
Other environment variables include the CGI variables, placed
there regardless of whether PHP is running as a server module or
CGI processor.
</simpara>
</sect2>
<sect2 id="language.variables.predefined.php">
<title>PHP variables</title>
<simpara>
These variables are created by PHP itself. The
<varname>$HTTP_*_VARS</varname> variables are available only if
the <link linkend="ini.track-vars">track_vars</link>
configuration is turned on. When enabled, the variables are
always set, even if they are empty arrays. This prevents
a malicious user from spoofing these variables.
</simpara>
<note>
<para>
As of PHP 4.0.3, <link
linkend="ini.track-vars">track_vars</link> is always turned on,
regardless of the configuration file setting.
</para>
</note>
<para>
If the <link
linkend="ini.register-globals">register_globals</link> directive
is set, then these variables will also be made available in the
global scope of the script; i.e., separate from the
<varname>$HTTP_*_VARS</varname> arrays. This feature should be
used with care, and turned off if possible; while the
<varname>$HTTP_*_VARS</varname> variables are safe, the bare
global equivalents can be overwritten by user input, with
possibly malicious intent. If you cannot turn off <link
linkend="ini.register-globals">register_globals</link>, you must
take whatever steps are necessary to ensure that the data you are
using is safe.
</para>
<para>
<variablelist>
<varlistentry>
<term>argv</term>
<listitem>
<simpara>
Array of arguments passed to the script. When the script is
run on the command line, this gives C-style access to the
command line parameters. When called via the GET method, this
will contain the query string.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>argc</term>
<listitem>
<simpara>
Contains the number of command line parameters passed to the
script (if run on the command line).
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>PHP_SELF</term>
<listitem>
<simpara>
The filename of the currently executing script, relative to
the document root. If PHP is running as a command-line
processor, this variable is not available.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>HTTP_COOKIE_VARS</term>
<listitem>
<simpara>
An associative array of variables passed to the current
script via HTTP cookies.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>HTTP_GET_VARS</term>
<listitem>
<simpara>
An associative array of variables passed to the current
script via the HTTP GET method.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>HTTP_POST_VARS</term>
<listitem>
<simpara>
An associative array of variables passed to the current
script via the HTTP POST method.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>HTTP_POST_FILES</term>
<listitem>
<simpara>
An associative array of variables containing information
about files uploaded via the HTTP POST method. See <link
linkend="features.file-upload.post-method">POST method
uploads</link> for information on the contents of
<varname>$HTTP_POST_FILES</varname>.
</simpara>
<para>
<varname>$HTTP_POST_FILES</varname> is available only in PHP
4.0.0 and later.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>HTTP_ENV_VARS</term>
<listitem>
<simpara>
An associative array of variables passed to the current
script via the parent environment.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>HTTP_SERVER_VARS</term>
<listitem>
<simpara>
An associative array of variables passed to the current
script from the HTTP server. These variables are analogous to
the Apache variables described above.
</simpara>
</listitem>
</varlistentry>
</variablelist>
</para>
</sect2>
</sect1>
<sect1 id="language.variables.scope">
<title>Variable scope</title>
<simpara>
The scope of a variable is the context within which it is defined.
For the most part all PHP variables only have a single scope.
This single scope spans included and required files as well. For
example:
</simpara>
<informalexample>
<programlisting role="php">
$a = 1;
include "b.inc";
</programlisting>
</informalexample>
<simpara>
Here the <varname>$a</varname> variable will be available within
the included <filename>b.inc</filename> script. However, within
user-defined functions a local function scope is introduced. Any
variable used inside a function is by default limited to the local
function scope. For example:
</simpara>
<informalexample>
<programlisting role="php">
$a = 1; /* global scope */
Function Test () {
echo $a; /* reference to local scope variable */
}
Test ();
</programlisting>
</informalexample>
<simpara>
This script will not produce any output because the echo statement
refers to a local version of the <varname>$a</varname> variable,
and it has not been assigned a value within this scope. You may
notice that this is a little bit different from the C language in
that global variables in C are automatically available to
functions unless specifically overridden by a local definition.
This can cause some problems in that people may inadvertently
change a global variable. In PHP global variables must be
declared global inside a function if they are going to be used in
that function. An example:
</simpara>
<informalexample>
<programlisting role="php">
$a = 1;
$b = 2;
Function Sum () {
global $a, $b;
$b = $a + $b;
}
Sum ();
echo $b;
</programlisting>
</informalexample>
<simpara>
The above script will output "3". By declaring
<varname>$a</varname> and <varname>$b</varname> global within the
function, all references to either variable will refer to the
global version. There is no limit to the number of global
variables that can be manipulated by a function.
</simpara>
<simpara>
A second way to access variables from the global scope is to use
the special PHP-defined <varname>$GLOBALS</varname> array. The
previous example can be rewritten as:
</simpara>
<informalexample>
<programlisting role="php">
$a = 1;
$b = 2;
Function Sum () {
$GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}
Sum ();
echo $b;
</programlisting>
</informalexample>
<simpara>
The <varname>$GLOBALS</varname> array is an associative array with
the name of the global variable being the key and the contents of
that variable being the value of the array element.
</simpara>
<simpara>
Another important feature of variable scoping is the
<emphasis>static</emphasis> variable. A static variable exists
only in a local function scope, but it does not lose its value
when program execution leaves this scope. Consider the following
example:
</simpara>
<informalexample>
<programlisting role="php">
Function Test () {
$a = 0;
echo $a;
$a++;
}
</programlisting>
</informalexample>
<simpara>
This function is quite useless since every time it is called it
sets <varname>$a</varname> to <literal>0</literal> and prints
"0". The <varname>$a</varname>++ which increments the
variable serves no purpose since as soon as the function exits the
<varname>$a</varname> variable disappears. To make a useful
counting function which will not lose track of the current count,
the <varname>$a</varname> variable is declared static:
</simpara>
<informalexample>
<programlisting role="php">
Function Test () {
static $a = 0;
echo $a;
$a++;
}
</programlisting>
</informalexample>
<simpara>
Now, every time the Test() function is called it will print the
value of <varname>$a</varname> and increment it.
</simpara>
<simpara>
Static variables also provide one way to deal with recursive
functions. A recursive function is one which calls itself. Care
must be taken when writing a recursive function because it is
possible to make it recurse indefinitely. You must make sure you
have an adequate way of terminating the recursion. The following
simple function recursively counts to 10, using the static
variable <varname>$count</varname> to know when to stop:
</simpara>
<informalexample>
<programlisting role="php">
Function Test () {
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
Test ();
}
$count--;
}
</programlisting>
</informalexample>
</sect1>
<sect1 id="language.variables.variable">
<title>Variable variables</title>
<simpara>
Sometimes it is convenient to be able to have variable variable
names. That is, a variable name which can be set and used
dynamically. A normal variable is set with a statement such as:
</simpara>
<informalexample>
<programlisting role="php">
$a = "hello";
</programlisting>
</informalexample>
<simpara>
A variable variable takes the value of a variable and treats that
as the name of a variable. In the above example,
<emphasis>hello</emphasis>, can be used as the name of a variable
by using two dollar signs. i.e.
</simpara>
<informalexample>
<programlisting role="php">
$$a = "world";
</programlisting>
</informalexample>
<simpara>
At this point two variables have been defined and stored in the
PHP symbol tree: <varname>$a</varname> with contents "hello" and
<varname>$hello</varname> with contents "world". Therefore, this
statement:
</simpara>
<informalexample>
<programlisting role="php">
echo "$a ${$a}";
</programlisting>
</informalexample>
<simpara>
produces the exact same output as:
</simpara>
<informalexample>
<programlisting>
echo "$a $hello";
</programlisting>
</informalexample>
<simpara>
i.e. they both produce: <computeroutput>hello world</computeroutput>.
</simpara>
<simpara>
In order to use variable variables with arrays, you have to
resolve an ambiguity problem. That is, if you write
<varname>$$a[1]</varname> then the parser needs to know if you
meant to use <varname>$a[1]</varname> as a variable, or if you
wanted <varname>$$a</varname> as the variable and then the [1]
index from that variable. The syntax for resolving this ambiguity
is: <varname>${$a[1]}</varname> for the first case and
<varname>${$a}[1]</varname> for the second.
</simpara>
</sect1>
<sect1 id="language.variables.external">
<title>Variables from outside PHP</title>
<sect2 id="language.variables.external.form">
<title>HTML Forms (GET and POST)</title>
<simpara>
When a form is submitted to a PHP script, any variables from that
form will be automatically made available to the script by
PHP. If the <link linkend="ini.track-vars">track_vars</link>
configuration option is turned on, then these variables will be
located in the associative arrays
<varname>$HTTP_POST_VARS</varname>,
<varname>$HTTP_GET_VARS</varname>, and/or
<varname>$HTTP_POST_FILES</varname>, according to the
source of the variable in question.
</simpara>
<para>
For more information on these variables, please read <link
linkend="language.variables.predefined">Predefined
variables</link>.
</para>
<para>
<example>
<title>Simple form variable</title>
<programlisting role="php">
<form action="foo.php" method="post">
Name: <input type="text" name="username"><br>
<input type="submit">
</form>
</programlisting>
</example>
</para>
<para>
When the above form is submitted, the value from the text input
will be available in
<varname>$HTTP_POST_VARS['username']</varname>. If the <link
linkend="ini.register-globals">register_globals</link>
configuration directive is turned on, then the variable will also
be available as <varname>$username</varname> in the global scope.
</para>
<simpara>
PHP also understands arrays in the context of form variables. You
may, for example, group related variables together, or use this
feature to retrieve values from a multiple select
input:
</simpara>
<para>
<example>
<title>More complex form variables</title>
<programlisting role="php">
<form action="array.php" method="post">
Name: <input type="text" name="personal[name]"><br>
Email: <input type="text" name="personal[email]"><br>
Beer: <br>
<select multiple name="beer[]">
<option value="warthog">Warthog
<option value="guinness">Guinness
<option value="stuttgarter">Stuttgarter Schwabenbräu
</select>
<input type="submit">
</form>
</programlisting>
</example>
</para>
<para>
In PHP 3, the array form variable usage is limited to
single-dimensional arrays. In PHP 4, no such restriction applies.
</para>
<sect3 id="language.variables.external.form.submit">
<title>IMAGE SUBMIT variable names</title>
<simpara>
When submitting a form, it is possible to use an image instead
of the standard submit button with a tag like:</simpara>
<informalexample>
<programlisting role="php">
<input type=image src="image.gif" name="sub">
</programlisting>
</informalexample>
<simpara>
When the user clicks somewhere on the image, the accompanying
form will be transmitted to the server with two additional
variables, sub_x and sub_y. These contain the coordinates of the
user click within the image. The experienced may note that the
actual variable names sent by the browser contains a period
rather than an underscore, but PHP converts the period to an
underscore automatically.
</simpara>
</sect3>
</sect2>
<sect2 id="language.variables.external.cookies">
<title>HTTP Cookies</title>
<simpara>
PHP transparently supports HTTP cookies as defined by <ulink
url="&spec.cookies;">Netscape's Spec</ulink>. Cookies are a
mechanism for storing data in the remote browser and thus
tracking or identifying return users. You can set cookies using
the <function>SetCookie</function> function. Cookies are part of
the HTTP header, so the SetCookie function must be called before
any output is sent to the browser. This is the same restriction
as for the <function>header</function> function. Any cookies
sent to you from the client will automatically be turned into a
PHP variable just like GET and POST method data.</simpara>
<simpara>
If you wish to assign multiple values to a single cookie, just
add <emphasis>[]</emphasis> to the cookie name. For
example:
</simpara>
<informalexample>
<programlisting role="php">
SetCookie ("MyCookie[]", "Testing", time()+3600);
</programlisting>
</informalexample>
<simpara>
Note that a cookie will replace a previous cookie by the same
name in your browser unless the path or domain is different. So,
for a shopping cart application you may want to keep a counter
and pass this along. i.e.
</simpara>
<example>
<title>SetCookie Example</title>
<programlisting role="php">
$Count++;
SetCookie ("Count", $Count, time()+3600);
SetCookie ("Cart[$Count]", $item, time()+3600);
</programlisting>
</example>
</sect2>
<sect2 id="language.variables.external.environment">
<title>Environment variables</title>
<para>
PHP automatically makes environment variables available as normal
PHP variables.
<informalexample>
<programlisting role="php">
echo $HOME; /* Shows the HOME environment variable, if set. */
</programlisting>
</informalexample>
</para>
<para>
Since information coming in via GET, POST and Cookie mechanisms
also automatically create PHP variables, it is sometimes best to
explicitly read a variable from the environment in order to make
sure that you are getting the right version. The
<function>getenv</function> function can be used for this. You
can also set an environment variable with the
<function>putenv</function> function.
</para>
</sect2>
<sect2 id="language.variables.external.dot-in-names">
<title>Dots in incoming variable names</title>
<para>
Typically, PHP does not alter the names of variables when they
are passed into a script. However, it should be noted that the
dot (period, full stop) is not a valid character in a PHP
variable name. For the reason, look at it:
<programlisting role="php">
$varname.ext; /* invalid variable name */
</programlisting>
Now, what the parser sees is a variable named
<varname>$varname</varname>, followed by the string concatenation
operator, followed by the barestring (i.e. unquoted string which
doesn't match any known key or reserved words) 'ext'. Obviously,
this doesn't have the intended result.
</para>
<para>
For this reason, it is important to note that PHP will
automatically replace any dots in incoming variable names with
underscores.
</para>
</sect2>
<sect2 id="language.variables.determining-type-of">
<title>Determining variable types</title>
<para>
Because PHP determines the types of variables and converts them
(generally) as needed, it is not always obvious what type a given
variable is at any one time. PHP includes several functions
which find out what type a variable is. They are
<function>gettype</function>, <function>is_long</function>,
<function>is_double</function>, <function>is_string</function>,
<function>is_array</function>, and
<function>is_object</function>.
</para>
</sect2>
</sect1>
</chapter>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"../../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
-->
|