ae Sun May 19 22:34:33 2002 EDT Modified files: /phpdoc-pt_BR/language variables.xml /phpdoc-pt_BR translation.xml Log: language.xml review
Index: phpdoc-pt_BR/language/variables.xml diff -u phpdoc-pt_BR/language/variables.xml:1.7 phpdoc-pt_BR/language/variables.xml:1.8 --- phpdoc-pt_BR/language/variables.xml:1.7 Sat Apr 20 03:18:19 2002 +++ phpdoc-pt_BR/language/variables.xml Sun May 19 22:34:33 2002 @@ -1,17 +1,14 @@ <?xml version="1.0" encoding="iso-8859-1"?> -<!-- EN-Revision: 1.2 Maintainer: andre_ae Status: working --> +<!-- EN-Revision: 1.46 Maintainer: ae Status: ready --> <chapter id="language.variables"> - <title>Variables</title> - + <title>Variáveis</title> + <sect1 id="language.variables.basics"> - <title>Basics</title> + <title>Introdução</title> <simpara> - As variáveis no PHP são representadas por um cifrão($) seguido pelo - nome da variável. Os nomes de variável no PHP fazem distinção entre - maiúsculas e minúsculas. - Variables in PHP are represented by a dollar sign followed by the - name of the variable. The variable name is case-sensitive. + As variáveis no PHP são representadas por um cifrão ($) seguido pelo + nome da variável. Os nomes de variável no PHP fazem distinção entre maiúsculas e +minúsculas. </simpara> <para> @@ -21,81 +18,90 @@ expressão regular isto poderia ser representado desta forma: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*' </para> - + <note> <simpara> - Para nosso propósito aqui, letras são a-z, A-Z e os caracteres + Para nossos propósitos, as letras a-z, A-Z e os caracteres ASCII de 127 a 255 (0x7f-0xff). </simpara> </note> <para> <informalexample> - <programlisting role="php"> + <programlisting role="php"> +<![CDATA[ $var = "Bob"; $Var = "Joe"; -echo "$var, $Var"; // imprime "Bob, Joe" +echo "$var, $Var"; // exibe "Bob, Joe" -$4site = 'not yet'; // inválido; começa com algarismo -$_4site = 'not yet'; // válido; começa com sublinhado -$täyte = 'mansikka'; // válido; 'ä' é ASCII 228. +$4site = 'not yet'; // inválido; começa com um número +$_4site = 'not yet'; // válido; começa com um sublinhado +$täyte = 'mansikka'; // válido; 'ä' é um caracter ASCII 228. +]]> </programlisting> </informalexample> </para> <para> - No PHP 3 as variáveis são sempre atribuídas por valor. Isto significa - dizer que quando você atribui uma expressão a uma variável, o valor + No PHP 3, as variáveis são sempre atribuídas por valor. Isto significa + que quando você atribui uma expressão a uma variável, o valor da expressão original é copiado integralmente para a variável de destino. - Isto significa que, após atribuir o valor de uma variável a - outra, a alteração de uma destas variáveis não afetará a outra. - Para mairoes informações sobre este tipo de atribuição, veja <link + Isto significa também que, após atribuir o valor de uma variável a + outra, a alteração de uma destas variáveis + não afetará a outra. Para maiores informações sobre este tipo de + atribuição, veja <link linkend="language.expressions">Expressões</link>. </para> <para> - PHP 4 oferece um outro meio de atribuir valores a variáveis: - <emphasis>atribuição por referência</emphasis>. Isto significa que - a nova variável simplesmente referencia (em outras palavras, "torna-se - um apelido para" ou "aponta para") a variável original. Alterações na - nova variável afetam a original e vice versa. Isto significa também que - nenhuma cópia é realizada, de modo que a atribuição ocorre mais rapidamente. - Entretanto, qualquer aumento de velocidade só será realmente notado - em *loops* complexos ou em atribuições de grandes matrizes (*arrays*) ou objetos. + O PHP 4 oferece um outro meio de atribuir valores a variáveis: a + <emphasis>atribuição por referência</emphasis>. Isto significa que + a nova variável simplesmente referencia (em outras palavras, "torna-se + um apelido para" ou "aponta para") a variável original. Alterações na + nova variável afetam a original e vice versa. Isto significa também que + nenhuma cópia é realizada, de modo que a atribuição ocorre mais rapidamente. + Entretanto, qualquer aumento de velocidade só será realmente notado + em *loops* complexos ou em atribuições de grandes matrizes (*arrays*) ou objetos. </para> <para> - Para atribuir por referência, simplesmente adicione um e-comercial (&) - na frente do nome da variável que estiver sendo atribuída (variável de origem) - Por exemplo, o trecho de código abaixo imprime 'My name is Bob' duas vezes: + Para atribuir por referência, simplesmente adicione um e-comercial (&) + na frente do nome da variável que estiver sendo atribuída (variável + de origem) Por exemplo, o trecho de código abaixo imprime 'My + name is Bob' duas vezes: <informalexample> <programlisting role="php"> -<?php +<![CDATA[ +<?php $foo = 'Bob'; // Atribui o valor 'Bob' a variável $foo -$bar = &$foo; // Referecia $foo através de $bar. +$bar = &$foo; // Referecia $foo através de $bar. $bar = "My name is $bar"; // Altera $bar... -echo $foo; // $foo é alterada também. echo $bar; -?> +echo $foo; // $foo é alterada também. +?> +]]> </programlisting> </informalexample> </para> <para> - Uma observação importante a se fazer é que somente variáveis - nomeadas podem ser atribuídas por referência. + Uma observação importante a se fazer: somente variáveis + nomeadas podem ser atribuídas por referência. <informalexample> <programlisting role="php"> -<?php +<![CDATA[ +<?php $foo = 25; -$bar = &$foo; // Esta atribuição é válida. -$bar = &(24 * 7); // Inválido; referencia uma expressão sem nome. +$bar = &$foo; // Esta atribuição é válida. +$bar = &(24 * 7); // Inválido; referencia uma expressão sem nome. -function test() { +function test() +{ return 25; } -$bar = &test(); // Inválido. -?> +$bar = &test(); // Inválido. +?> +]]> </programlisting> </informalexample> </para> @@ -104,920 +110,669 @@ <sect1 id="language.variables.predefined"> <title>Variáveis Predefinidas</title> - - <simpara> - PHP oferece um grande número de variáveis predefinidas para qualquer - script que ele execute. Muitas destas variáveis, entretanto, não podem - ser completamente documentadas uma vez dependem de diversos fatores como - o servidor no qual scripts são executados, a versão e configuração deste - servidor, dentre outros fatores. Algumas destas variáveis não estarão - disponíveis quando o PHP for executado na linha de comando. - </simpara> <simpara> - A despeito destes fatores, temos aqui uma lista de variáveis predefinidas - disponíveis sob uma instalação padrão do PHP 3 executado como um módulo - em uma instalação padrão do <ulink url="&url.apache;">Apache</ulink> 1.3.6. + O PHP oferece um grande número de variáveis predefinidas para qualquer script + que ele execute. Muitas destas variáveis, entretanto, não podem ser completamente + documentadas uma vez dependem de diversos fatores, como o servidor no qual +scripts são executados, a + versão e configuração deste servidor e outros. Algumas destas + variáveis não estarão disponíveis quando o PHP for executado na linha de + comando. Para uma lista destas variáveis, veja a seção + <link linkend="reserved.variables">Variáveis reservadas</link>. </simpara> - <simpara> - Para obter uma lista de todas as variáveis predefinidas (e um monte de - outras informações ú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> - + <warning> <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. + No PHP 4.2.0 e posteriores, a variedade de variáveis predefinidas + disponíveis no escopo global foi modificada. Parâmetros + individuais e variáveis do servidor <emphasis>por default não</emphasis> + são disponíveis diretamente no escopo global: elas são + colocadas dentro dos <link + linkend="language.variables.superglobals">arrays + superglobais</link>. </simpara> <simpara> - Other environment variables include the CGI variables, placed - there regardless of whether PHP is running as a server module or - CGI processor. + Você também pode forçar o antigo comportamento configurando <link + linkend="ini.register-globals">register_globals</link> para 'On' em + seu arquivo &php.ini;. </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. + Para maiores informações desta modificação, veja + o <ulink url="&url.php.release4.1.0;">PHP 4.1.0 Release + Announcement</ulink>. </simpara> + </warning> - <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> + <simpara> + Desde a versão 4.1.0, o PHP fornece um conjunto de arrays predefinidos + contendo as variáveis do servidor web (se aplicável), as + variáveis ambiente e as entradas do usuário. Esses novos arrays são especiais + pelo motivo que são automaticamente globais (significa que são automaticamente + disponíveis em qualquer escopo. Por causa disso, são também conhecidas como + 'autoglobais' ou 'superglobais' (Não há um mecanismo no PHP para + superglobais definidas pelo usuário) As superglobais são listadas abaixo. + Entretanto, para uma explicação de seu conteúdo e detalhes sobre + as variáveis predefinidas do PHP e sua natureza, veja a seção + <link linkend="reserved.variables">Variáveis Predefinidas</link>. + </simpara> - <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> - + <variablelist id="language.variables.superglobals"> + <title>Superglobais do PHP</title> <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> - + <term><link linkend="reserved.variables.globals">$GLOBALS</link></term> + <listitem> + <simpara> + Contém um referência para todas as variáveis que são atualmente + disponíveis dentro do escopo global do script. As chaves + desse array são os nomes das variáveis globais. + </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> + <term><link linkend="reserved.variables.server">$_SERVER</link></term> + <listitem> + <simpara> + Variáveis criadas pelo servidor web ou diretamente relacionadas + ao ambiente de execução do script atual. Análogo + ao antigo array <varname>$HTTP_SERVER_VARS</varname> (que + ainda continua disponível, mas em decadência). + </simpara> + </listitem> + </varlistentry> + <varlistentry> + <term><link linkend="reserved.variables.get">$_GET</link></term> + <listitem> + <simpara> + Variáveis postadas para o script via método HTTP GET. Análogo ao + antigo array <varname>$HTTP_GET_VARS</varname> (que + ainda continua disponível, mas em decadência). + </simpara> + </listitem> + </varlistentry> + <varlistentry> + <term><link linkend="reserved.variables.post">$_POST</link></term> + <listitem> + <simpara> + Variáveis postadas para o script via método HTTP POST. Análogo ao + antigo array <varname>$HTTP_POST_VARS</varname> (que + ainda continua disponível, mas em decadência). + </simpara> + </listitem> + </varlistentry> + <varlistentry> + <term><link linkend="reserved.variables.cookies">$_COOKIE</link></term> + <listitem> + <simpara> + Variáveis postadas para o script via cookies HTTP. Análogo ao + antigo array <varname>$HTTP_COOKIE_VARS</varname> (que + ainda continua disponível, mas em decadência). + </simpara> + </listitem> + </varlistentry> + <varlistentry> + <term><link linkend="reserved.variables.files">$_FILES</link></term> + <listitem> + <simpara> + Variáveis postadas para o script via transferência de arquivos HTTP. + Análogo ao antigo array + <varname>$HTTP_POST_FILES</varname> (que ainda + continua disponível, mas em decadência). Veja <link + linkend="features.file-upload.post-method">uploads via + método POST</link> para maiores informações. + </simpara> + </listitem> + </varlistentry> + <varlistentry> + <term><link linkend="reserved.variables.environment">$_ENV</link></term> + <listitem> + <simpara> + Variáveis disponíveis no script do ambiente de execução. Análogo ao + antigo array <varname>$HTTP_ENV_VARS</varname> (que + ainda continua disponível, mas em decadência). + </simpara> + </listitem> + </varlistentry> + <varlistentry> + <term><link linkend="reserved.variables.request">$_REQUEST</link></term> + <listitem> + <simpara> + Variáveis postadas para o script por todas os mecanismos de input, + e que não podem ter seu conteúdo garantido de qualquer forma. Note: quando +executando + da linha de comando, elas <emphasis>não</emphasis> incluem + as entidades <varname>argv</varname> e <varname>argc</varname>; + elas estão presentes no array <varname>$_SERVER</varname>. + A presença e a ordem de inclusão das variáveis nesse array + é definida de acordo com a diretiva de configuração <link + linkend="ini.variables-order">variables_order</link>. + Este array não tem um equivalente nas + versões anteriores do PHP 4.1.0. + </simpara> + </listitem> + </varlistentry> + <varlistentry> + <term><link linkend="reserved.variables.session">$_SESSION</link></term> + <listitem> + <simpara> + Variáveis que estão atualmente registradas na sessão do + script. Análogo ao antigo array + <varname>$HTTP_SESSION_VARS</varname> (que ainda + continua disponível, mas em decadência). Veja a sessão <link + linkend="ref.session">funções de manipulação de Sessões</link> + para maiores informações. + </simpara> + </listitem> + </varlistentry> + </variablelist> </sect1> <sect1 id="language.variables.scope"> - <title>Variable scope</title> + <title>Escopo de variáveis</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: + O escopo de uma variável é o contexto onde ela foi definida. + A maior parte das variáveis do PHP tem somente escopo local. + Este escopo local inclui os arquivos incluídos. Por + exemplo: </simpara> <informalexample> <programlisting role="php"> +<![CDATA[ $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> - + Aqui a variável <varname>$a</varname> estará disponível + no script incluído <filename>b.inc</filename>. Entretanto, com as + funções definidas pelo usuário, um escopo local é introduzido. Quaisquer + variáveis utilizadas dento da função é por default limitada dentro do + escopo local da função. Por exemplo: +</simpara> + <informalexample> - <programlisting role="php"> -$a = 1; /* global scope */ + <programlisting role="php"> +<![CDATA[ +$a = 1; /* escopo global */ -Function Test () { - echo $a; /* reference to local scope variable */ -} +function Teste() +{ + echo $a; /* referencia uma variável do escopo local (não definida) */ +} -Test (); +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: + Este script não produz nenhuma saída porque a instrução <function>echo</function> + refere-se a uma versão local da variável <varname>$a</varname>, + e ela não tem nenhum valor assimilado nesse escopo. Essa é uma + pequena diferença da linguagem C quando + variáveis globais são automaticamente disponíveis para + funções sem sobreescrever uma eventual definição local. + Isto causa problemas quando as pessoas mudam + inadivertidamente uma variável global. No PHP, as variáveis globais precisam ser + declaradas globais dentro de uma função se ela vai ser utilizada + naquela função. Um exemplo: </simpara> <informalexample> <programlisting role="php"> +<![CDATA[ $a = 1; $b = 2; -Function Sum () { +function Soma() +{ global $a, $b; $b = $a + $b; -} +} -Sum (); +Soma(); 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. + O script acima imprimirá "3". Declarando + <varname>$a</varname> e <varname>$b</varname> globais na + função, todas as referências a essas variáveis referem-se a + versão global. Não há um limite para o número de variáveis + globais que podem ser manipuladas por uma função. </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: + Uma segunda maneira de acessar variáveis do escopo global é utilizando + o array especial <varname>$GLOBALS</varname> definido pelo PHP. O + exemplo anterior poderia ser rescrito como: </simpara> <informalexample> <programlisting role="php"> +<![CDATA[ $a = 1; $b = 2; -Function Sum () { +function Soma() +{ $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"]; -} +} -Sum (); +Soma(); 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. + <varname>$GLOBALS</varname> é um array associativo em que + o nome das variáveis globais são suas chaves e o conteúdo dessas + variáveis são o valor do elemento do array. </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: + Outro recurso importante do escopo de variáveis é a + variável <emphasis>estática</emphasis>. Uma variável estática existe + somente no escopo local da função, mas ela não perde seu valor + quando o nível de execução do programa deixa o escopo. Considere o seguinte + exemplo: </simpara> <informalexample> <programlisting role="php"> -Function Test () { +<![CDATA[ +function Teste () +{ $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: + Essa função é inútil partindo de que cada vez que ela é chamada, ela + coloca em <varname>$a</varname> o valor <literal>0</literal> e imprime + "0". A instrução <varname>$a</varname>++ , que aumenta o valor da + variável não tem sentido desde que a função sai e a + variável <varname>$a</varname> desaparece. Para faze-la mais útil + como contadora sem deixar de perder o sua conta atual, + a variável <varname>$a</varname> é declarada como estática: </simpara> <informalexample> <programlisting role="php"> -Function Test () { +<![CDATA[ +function Teste() +{ 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. + Agora, cada vez que a função Teste() for chamada ele imprimirá o + valor de <varname>$a</varname> e o incrementará. </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: + Variáveis estáticas fornecem uma solução ideal para funções + recursivas. Uma função recursiva é aquela se chama a si mesma. Cuidados + especiais precisam ser tomados quando escrevendo funções recursivas porque é + possível que ela continue na recursão indefinidamente. Você tem de ter certeza + que há uma maneira segura de terminar a recursão. A seguinte + função recursiva conta até 10, utilizando a variável + estática <varname>$count</varname> para saber quando parar: </simpara> <informalexample> <programlisting role="php"> -Function Test () { +<![CDATA[ +function Teste() +{ static $count = 0; $count++; echo $count; - if ($count < 10) { + if ($count < 10) { Test (); } $count--; } +]]> </programlisting> </informalexample> </sect1> <sect1 id="language.variables.variable"> - <title>Variable variables</title> + <title>Variáveis variáveis</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: + As vezes é conveniente poder trabalhar com variáveis + variáveis. Isto é, nomes de variáveis que pode ser criadas e utilizadas + dinamicamente. Uma variável normal é criada numa instrução como: </simpara> <informalexample> <programlisting role="php"> +<![CDATA[ $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. + Uma variável variável pega o valor de uma variável e a trata como + o nome de uma variável. No exemplo acima, + <emphasis>hello</emphasis> pode ser utilizada como o nome de uma variável + utilizando dois sinais de cifrão: </simpara> <informalexample> <programlisting role="php"> +<![CDATA[ $$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: + Neste ponto, duas variáveis foram definidas e preservadas na + árvore de símbolos do PHP: <varname>$a</varname> contendo "hello" e + <varname>$hello</varname> contendo "world". Da mesma forma, esta + instrução: </simpara> <informalexample> <programlisting role="php"> +<![CDATA[ echo "$a ${$a}"; +]]> </programlisting> </informalexample> <simpara> - produces the exact same output as: + produz a mesma saida que: </simpara> <informalexample> - <programlisting> + <programlisting role="php"> +<![CDATA[ echo "$a $hello"; +]]> </programlisting> </informalexample> <simpara> - i.e. they both produce: <computeroutput>hello world</computeroutput>. + no caso: <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. + Para poder utilizar variáveis variáveis com arrays, você precisa + resolver um problema de ambigüidade. Assim, se você escrever + <varname>$$a[1]</varname> então o interpretador pode entender que + você quer usar <varname>$a[1]</varname> como uma variável ou que + você quer usar <varname>$$a</varname> como uma variável e [1] + como o índice dessa variável. A sintaxe para resolver essa ambigüidade + é <varname>${$a[1]}</varname> para o primeiro caso e + <varname>${$a}[1]</varname> para o segundo. </simpara> - + + <simpara> + Verifique que variáveis variáveis não podem ser utilizadas com as novas +superglobais do PHP. + Isto significa que você não pode fazer coisas como <varname>${$_GET}</varname>. +Se você está + procurando uma maneira de manipular as superglobais como as antigas + HTTP_*_VARS, você deve tentar <link +linkend="language.references">referenciá-las</link>. + </simpara> + </sect1> <sect1 id="language.variables.external"> - <title>Variables from outside PHP</title> + <title>Variáveis externas ao PHP</title> <sect2 id="language.variables.external.form"> - <title>HTML Forms (GET and POST)</title> + <title>Formulários HTML (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 + Quando um formulário é submetido para um script PHP, qualquer variável do + formulário será automaticamente disponível para o script pelo + PHP. Se a diretiva de configuração <link +linkend="ini.track-vars">track_vars</link> + estiver ativada, então essas variáveis estarão + localizadas nos arrays associativos <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. + <varname>$HTTP_GET_VARS</varname> e/ou + <varname>$HTTP_POST_FILES</varname>, de acordo com + a fonte da variável em questão. </simpara> <para> - For more information on these variables, please read <link - linkend="language.variables.predefined">Predefined - variables</link>. + Para maiores informações sobre essas veiáveis, veja <link + linkend="language.variables.predefined">Variáveis + Predefinidas</link>. </para> <para> <example> - <title>Simple form variable</title> + <title>Variáveis simples de formulários</title> <programlisting role="php"> -<form action="foo.php" method="post"> - Name: <input type="text" name="username"><br> - <input type="submit"> -</form> +<![CDATA[ +<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 + Quando o formulário é submetido, o valor da caixa de texto + estará disponível em + <varname>$HTTP_POST_VARS['username']</varname>. Se a diretiva de configuração +<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. + estiver ativada, então a estará disponível + a variável <varname>$username</varname> no escopo global. </para> + <note> + <para> + A diretiva de configuração <link +linkend="ini.magic-quotes-gpc">magic_quotes_gpc</link> + afeta os valores de GET, POST e Cookies. Se + estiver ativada, o valor (It's "PHP!") se tornará automaticamente (It\'s +\"PHP!\"). + Escaping é necessário para inserção em bancos de dados. Veja também + <function>addslashes</function>, <function>stripslashes</function> e + <link linkend="ini.magic-quotes-sybase">magic_quotes_sybase</link>. + </para> + </note> + <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: + O PHP entende arrays no contexto de variáveis de formulários + (veja o <link linkend="faq.html">FAQ</link> relacionado). Você pode, + por exemplo, agrupar variáveis relacionadas juntas, ou usar + esse recurso para receber valores de um campo de seleção múltipla. </simpara> <para> <example> - <title>More complex form variables</title> + <title>Variáveis de formulários complexos</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> +<![CDATA[ +<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. + No PHP 3, os arrays variáveis de formulários eram limitados + a uma dimensão. No PHP 4, essa restrição não existe mais. </para> <sect3 id="language.variables.external.form.submit"> - <title>IMAGE SUBMIT variable names</title> + <title>Nomes de variáveis SUBMIT IMAGE</title> <simpara> - When submitting a form, it is possible to use an image instead - of the standard submit button with a tag like:</simpara> + Quando submetendo um formulário, é possível de se utilizar imagens ao invés + do botão de submit padrão com uma tag do tipo:</simpara> <informalexample> <programlisting role="php"> -<input type=image src="image.gif" name="sub"> +<![CDATA[ +<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. + Quando o usuário clica em algum lugar da imagem, o formulário + que o acompanha é transmitido para o servidor com duas variáveis + adicionais, sub_x e sub_y. Eles contém a coordenadas do + clique do usuário na imagem. Os mais experientes percebem que os + atuais nomes dessas variáveis enviados pelo browser contém um ponto + ao invés de um sublinhado, mas o PHP converte o ponto para um + sublinhado automaticamente. </simpara> </sect3> </sect2> <sect2 id="language.variables.external.cookies"> - <title>HTTP Cookies</title> + <title>Cookies HTTP</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: + O PHP suporta transparentemente cookies HTTP como os definidos pela <ulink + url="&spec.cookies;">especificação da Netscape</ulink>. Cookies são um + mecanismo de armazenamento de dados no browser cliente e permite + o rastreamento ou identificação do retorno de usuários. Você pode criar cookies +com + a função <function>setcookie</function>. Cookies são parte do + header HTTP, então, a função <function>setcookie</function> precisa ser chamada +antes + de qualquer saída ser enviada ao browser. Esta é a mesma restrição + da função <function>header</function>. Quaisquer cookies + enviados para você do cliente será automaticamente transformada em + variáveis PHP assim como os dados postados via GET ou POST.</simpara> + + <simpara> + Se você precisa armazenar múltiplos valores em um único cookies, basta + apenas acrescentar <emphasis>[]</emphasis> ao nome do cookie. Por + exemplo: </simpara> <informalexample> <programlisting role="php"> -SetCookie ("MyCookie[]", "Testing", time()+3600); +<![CDATA[ +setcookie("MeuCookie[]", "Testando", 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. + Note que um cookie substituirá um anterior com o mesmo + nome em seu browser mesmo se o nome ou o caminho for diferente. Então, + para uma aplicação de carrinho de compras em que você quer ter um contador + e repassá-lo: </simpara> <example> - <title>SetCookie Example</title> + <title>Exemplo SetCookie</title> <programlisting role="php"> +<![CDATA[ $Count++; -SetCookie ("Count", $Count, time()+3600); -SetCookie ("Cart[$Count]", $item, time()+3600); +setcookie("Count", $Count, time()+3600); +setcookie("Cart[$Count]", $item, time()+3600); +]]> </programlisting> </example> </sect2> <sect2 id="language.variables.external.environment"> - <title>Environment variables</title> + <title>Variáveis ambiente</title> <para> - PHP automatically makes environment variables available as normal - PHP variables. - + O PHP automaticamente torna as variáveis de ambiente disponíveis como variáveis + PHP normais. + <informalexample> <programlisting role="php"> -echo $HOME; /* Shows the HOME environment variable, if set. */ +<![CDATA[ +echo $HOME; /* Exibe a variável ambiente HOME, se existente. */ +]]> </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. + Desde que as informações oriundas dos mecanismos GET, POST ou Cookie + são automaticamente criadas como variáveis PHP, as vezes é melhor + fazer a leitura direto do ambiente de execução para ter certeza que + a esta obtendo a versão correta. A + função <function>getenv</function> pode ser utilizada para isso. Você + também pode criar uma variável de ambiente com a + função <function>putenv</function>. </para> </sect2> <sect2 id="language.variables.external.dot-in-names"> - <title>Dots in incoming variable names</title> + <title>Pontos em nomes de variáveis postadas</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: + Normalmente o PHP não altera o nome de variáveis quando elas + são passadas para o script. Entretanto, é necessário notar que o + ponto (ponto final) não é um caracter válido no nomes de + variáveis do PHP. Para ilustrar, veja o seguinte exemplo: <programlisting role="php"> -$varname.ext; /* invalid variable name */ +<![CDATA[ +$varname.ext; /* nome de variável inválido */ +]]> </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. + Dessa forma, o interpretador entende isso como uma variável nomeada + <varname>$varname</varname>, seguida do operador de concatenação + de strings, seguida de um identificador (uma string não delimitada que + não bate com nenhuma palavra chave ou reservada) 'ext'. Obviamente, + isso não tem os resultados pretendidos. </para> <para> - For this reason, it is important to note that PHP will - automatically replace any dots in incoming variable names with - underscores. + Nessa situação, é importante saber que o PHP + automaticamente substituirá qualquer ponto nos nomes de variáveis recebidas com + sublinhados. </para> </sect2> <sect2 id="language.variables.determining-type-of"> - <title>Determining variable types</title> + <title>Determinando o tipo das variáveis</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>. + Porque o PHP determina os tipos de variáveis e faz conversões + (geralmente) quando necessárias, nem sempre é óbvio o tipo de uma variável + tem em todos os momentos. O PHP incluí várias funções + que permitem determinar qual o tipo de uma variável. Elas são + <function>gettype</function>, <function>is_array</function>, + <function>is_float</function>, <function>is_int</function>, + <function>is_object</function>, e + <function>is_string</function>. </para> </sect2> @@ -1025,20 +780,23 @@ </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 +<!-- 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: - --> +sgml-parent-document:nil +sgml-default-dtd-file:"../../manual.ced" +sgml-exposed-tags:nil +sgml-local-catalogs:nil +sgml-local-ecat-files:nil +End: +vim600: syn=xml fen fdm=syntax fdl=2 si +vim: et tw=78 syn=sgml +vi: ts=1 sw=1 +--> Index: phpdoc-pt_BR/translation.xml diff -u phpdoc-pt_BR/translation.xml:1.12 phpdoc-pt_BR/translation.xml:1.13 --- phpdoc-pt_BR/translation.xml:1.12 Mon May 13 22:41:13 2002 +++ phpdoc-pt_BR/translation.xml Sun May 19 22:34:33 2002 @@ -7,7 +7,7 @@ </intro> <translators> <person name="Renato Arruda" email="[EMAIL PROTECTED]" nick="rarruda" cvs="yes"/> - <person name="André L F S Bacci" email="[EMAIL PROTECTED]" nick="andre_ae" cvs="yes"/> + <person name="André L F S Bacci" email="[EMAIL PROTECTED]" nick="ae" +cvs="yes"/> <person name="Anderson Fortaleza" cvs="yes" email="[EMAIL PROTECTED]" nick="phaser" cvs="yes"/> <person name="João Prado Maia" email="[EMAIL PROTECTED]" nick="jpm" cvs="yes"/> <person name="Claudio Pereira" email="[EMAIL PROTECTED]" nick="cpereira" cvs="yes"/> @@ -18,9 +18,8 @@ <file name="chapters/config.xml" person="rarruda" type="review" date="04.27.2002"/> <file name="reference/mysql/reference.xml" person="rarruda" type="translation" date="04.18.2002"/> <file name="reference/math/functions/*" person="rarruda" type="translation" date="04.28.2002"/> - <file name="language/variables.xml" person="cpereira" type="translation" date=""/> <file name="reference/math/reference.xml" person="kappu" type="translation" date="02.02.2002"/> <file name="reference/pgsql/reference.xml" person="phaser" type="translation" date="04.26.2002"/> - <file name="language/*" person="andre_ae" type="review (1 of 9)" date="05.12.2002"/> + <file name="language/*" person="ae" type="review (3 of 10)" +date="05.12.2002"/> </work-in-progress> </translation>