From cffa746463c532364df38b40d9cb669d95f604f2 Mon Sep 17 00:00:00 2001 From: Thomas Gonzalez Miranda Date: Wed, 20 Nov 2002 12:19:11 +0000 Subject: [PATCH] i'm right? git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@105021 c90b9560-bf6c-de11-be94-00142212c4b1 --- appendices/migration.xml | 267 ++++---- appendices/migration4.xml | 470 +++++++------- appendices/phpdevel.xml | 684 +++++++++++---------- appendices/reserved.constants.core.xml | 12 +- appendices/reserved.constants.standard.xml | 10 +- appendices/resources.xml | 26 +- appendices/tokens.xml | 17 +- 7 files changed, 752 insertions(+), 734 deletions(-) diff --git a/appendices/migration.xml b/appendices/migration.xml index 036b7b68e1..938b5cbfec 100644 --- a/appendices/migration.xml +++ b/appendices/migration.xml @@ -1,95 +1,94 @@ - + - Migrating from PHP/FI 2 to PHP 3 + Mirgrando do PHP/FI para o PHP 3
- About the incompatibilities in 3.0 + Sobre as incompatibilidades do 3.0 - PHP 3.0 is rewritten from the ground up. It has a proper parser - that is much more robust and consistent than 2.0's. 3.0 is also - significantly faster, and uses less memory. However, some of - these improvements have not been possible without compatibility - changes, both in syntax and functionality. + PHP 3.0 foi totalmente reescrito. Ele tem um parser apropriado + que é muito mais robusto e consistente que o da versão 2.0. 3.0 + é também significamente mais rápido, e usa menos memória. Entretanto + algumas dessas melhorias não seriam possíveis sem mudanças na compatibilidade, + na sintaxe e na funcionalidade. - In addition, PHP's developers have tried to clean up both PHP's - syntax and semantics in version 3.0, and this has also caused some - incompatibilities. In the long run, we believe that these changes - are for the better. + Além do mais, os desenvolvedores do PHP tentaram limpar ambas + sintaxe e semânticas da versão 3.0 do PHP, e isto também traz algumas + incompatbilidades. A longo prazo, nós acreditamos que estas mudanças + são para melhor. - This chapter will try to guide you through the incompatibilities - you might run into when going from PHP/FI 2.0 to PHP 3.0 and help - you resolve them. New features are not mentioned here unless - necessary. + Este capítulo tentará guiar você com as incompatibilidades que você + encontrará quando estiver migrando do PHP/FI 2.0 para o PHP 3.0 e + ajudará a resolver elas. Novas características não são mencionadas aqui + a menos que seja necessário. - A conversion program that can automatically convert your old - PHP/FI 2.0 scripts exists. It can be found in the - convertor subdirectory of the PHP 3.0 - distribution. This program only catches the syntax changes though, - so you should read this chapter carefully anyway. + Um programa que converte automaticamente seus scripts em PHP/FI 2.0 existe. + Ele pode ser encontrado no subdiretório convertor + da distribuição do PHP 3.0. Este programa apenas capta alterações de sintaxe, + portanto você deve ler atentamente este capítulo.
- Start/end tags + Tags de Começo/fim - The first thing you probably will notice is that PHP's start and end - tags have changed. The old <? > form has been - replaced by three new possible forms: + A primeira coisa que você provavelmente irá reparar é que as tags de + começo e fim do PHP mudaram. O velho foi <? > + modificado para três formas possíveis: - Migration: old start/end tags + Migrando: da velha tag começo/fim + ]]> - As of version 2.0, PHP/FI also supports this variation: + Como na versão 2.0, PHP/FI também suporta esta variação: - Migration: first new start/end tags + Migrando: primeira forma das tags começo/fim + ]]> - Notice that the end tag now consists of a question mark and a - greater-than character instead of just greater-than. However, if - you plan on using XML on your server, you will get problems with - the first new variant, because PHP may try to execute the XML - markup in XML documents as PHP code. Because of this, the - following variation was introduced: + Repare que a tag de fechamento agora consiste em um sinal de interrogação e uma + tag de fechamento e não apenas em uma tag de fechamento. Entretanto, se + você planeja usar XML no seu servidor, você obeterá alguns problemas com a + nova variação, porque o PHP pode tentar executar as tags de marcação dos + documentos em XML como códigos PHP. Por causa disto, a seguinte modificação + foi adicionada: - Migration: second new start/end tags + Migrando: segunda forma das tags começo/fim + ]]> - Some people have had problems with editors that don't understand - the processing instruction tags at all. Microsoft FrontPage is one - such editor, and as a workaround for these, the following variation - was introduced as well: + Algumas pessoas obtiveram problemas com editores que não entendem + todas as tags de processamento. O Microsoft Frontpage é um destes editores, + e pensando nestes editores, foi adicionado mais uma modificação que é mostrada + abaixo: - Migration: third new start/end tags + Migrando: terceira forma das tags começo/fim - echo "This is PHP 3.0 code!\n"; + echo "Este é um código em PHP 3.0!\n"; ]]> @@ -99,67 +98,66 @@
- if..endif syntax + sintaxe if..endif - The `alternative' way to write if/elseif/else statements, using if(); - elseif(); else; endif; cannot be efficiently implemented without - adding a large amount of complexity to the 3.0 parser. Because of - this, the syntax has been changed: + A maneira 'alternativa' de escrever as instruções if/elseif/else , usando if(); + elseif(); else; endif; não puderam ser eficientemente implementadas sem adicionar + uma quantidade grande de complexidade ao parser 3.0. Por causa disso, a sintaxe foi + alterada para: - Migration: old if..endif syntax + Migrando: velha sintaxe if..endif - Migration: new if..endif syntax + Migrando: nova sintaxe if..endif - Notice that the semicolons have been replaced by colons in all - statements but the one terminating the expression (endif). + Repare que todos os pontos-e-vírgulas foram trocados por dois-pontos em todas + as instruções, exceto na instrução de fechamento (endif).
- while syntax + sintaxe while - Just like with if..endif, the syntax of while..endwhile has changed - as well: + Assim como o if...endif, a sintaxe do while...endwhile foi alterada: - Migration: old while..endwhile syntax + Migrando: a velha sintaxe do while..endwhile - Migration: new while..endwhile syntax + Migrando: nova sintaxe do while..endwhile @@ -168,22 +166,22 @@ endwhile; - If you use the old while..endwhile syntax in PHP 3.0, - you will get a never-ending loop. + Se você usar a velha sintaxe do while...endwhile no PHP 3.0, + você irá obter um loop que nunca-termina.
- Expression types + Tipos de Expressões - PHP/FI 2.0 used the left side of expressions to determine what type - the result should be. PHP 3.0 takes both sides into account when - determining result types, and this may cause 2.0 scripts to behave - unexpectedly in 3.0. + O PHP/FI 2.0 usa o lado esquerdo das expressões para determinar qual o tipo + de resultado que deve retornar. O PHP 3.0 examina ambos os lados quando + determina os tipos de resultados, e isto pode fazer com que scripts da versão + 2.0 comportem-se inesperadamente. - Consider this example: + Considere este exemplo: - In PHP/FI 2.0, this would display both of $a's indices. In PHP - 3.0, it wouldn't display anything. The reason is that in PHP 2.0, - because the left argument's type was string, a string comparison - was made, and indeed "" does not equal - "0", and the loop went through. In PHP 3.0, - when a string is compared with an integer, an integer comparison is - made (the string is converted to an integer). This results in - comparing atoi("") which is - 0, and variablelist which is - also 0, and since 0==0, the - loop doesn't go through even once. + No PHP/FI 2.0, isto mostraria ambos os índices de $a. No PHP 3.0, + isto não mostraria nada. A razão é que no PHP 2.0, é porque os argumentos + da esquerda eram do tipo string, então uma comparação de string foi feita, + e certamente "" não é igual à "0", e o + laço é completado. No PHP 3.0, quando uma string é comparada com um inteiro, uma + comparação de inteiro é feita (a string é convertida para inteiro). Isto resultado em uma + comparação em que atoi("") é 0, e variablelist + também é 0, deste que 0==0, o loop não executa mais de uma vez. - The fix for this is simple. Replace the while statement with: + A correção para iso é simples. Troque aquele while por:
- Error messages have changed + Mensagens de erro foram alteradas - PHP 3.0's error messages are usually more accurate than 2.0's were, - but you no longer get to see the code fragment causing the error. - You will be supplied with a file name and a line number for the - error, though. + No PHP 3.0 as mensagens de erro geralmente são mais exatadas do que as do PHP 2.0, + mas você não verá mais o fragmento de código que contém o erro. Você será notificado + com o nome do arquivo e o número da linha onde ocorreu o erro.
Short-circuited boolean evaluation - In PHP 3.0 boolean evaluation is short-circuited. This means that - in an expression like (1 || test_me()), the - function test_me would not be executed since - nothing can change the result of the expression after the - 1. + No PHP 3.0 a avaliação booleana é short-circuited. Isto significa que + uma expressão como esta (1 || teste_me()), da função + teste_me não seria executada porque nada pode mudar + o resultado da expressão após 1. - This is a minor compatibility issue, but may cause unexpected - side-effects. + Esta é uma pequena incompatibilidade, mas poderá causar side-effects + inesperados.
- Function &true;/&false; return values + Funções &true;/&false; retornam valores - Most internal functions have been rewritten so they return &true; - when successful and &false; when failing, as opposed to 0 and -1 in - PHP/FI 2.0, respectively. The new behaviour allows for more - logical code, like $fp = fopen("/your/file") or - fail("darn!");. Because PHP/FI 2.0 had no clear rules - for what functions should return when they failed, most such - scripts will probably have to be checked manually after using the - 2.0 to 3.0 convertor. + A maioria das funções foram reescritas sendo assim, retornam &true; + quando obtém sucesso e &false; quando falham, ao contrário de 0 e -1 no + PHP/FI 2.0, respectivamente. O novo comportamento permite um código mais + lógico, como $fp = fopen("/seu/arquivo") or fail("merda!");. + Porque o PHP/FI 2.0 não tem regras claras quanto ao que a função deverá retornar + caso falhe, muitos scripts provavelmente deverão ser checados manualmente após usar + o conversor de 2.0 para 3.0. - Migration from 2.0: return values, old code + Migrando do 2.0: retornando valores, código antigo \n"); + echo("Não foi possível abrir $arquivo para leitura
\n"); endif; ]]>
- Migration from 2.0: return values, new code + Migrando do 2.0: retornando valores, novo código \n"); +$fp = @fopen($arquivo, "r") or print("Não foi possível abrir $arquivo para leitura
\n"); ]]>
@@ -285,65 +277,60 @@ $fp = @fopen($file, "r") or print("Could not open $file for reading
\n");
- Other incompatibilities + Outras incompatibilidades - The PHP 3.0 Apache module no longer supports Apache versions - prior to 1.2. Apache 1.2 or later is required. + O módulo do PHP 3.0 para o Apache não suporta versões anteriores à 1.2. + Apache 1.2 ou atual é requerido. - echo no longer supports a format string. - Use the printf function instead. + echo não suporta mais strings formatadas. + Use a função printf para isto. - In PHP/FI 2.0, an implementation side-effect caused - $foo[0] to have the same effect as - $foo. This is not true for PHP 3.0. + No PHP/FI 2.0, uma execução "side-effect" faz com que $foo[0] + tenha o mesmo efeito que $foo. No PHP 3.0 isto não é verdadeiro. - Reading arrays with $array[] is no longer - supported + Ler arrays com $array[] não é mais + suportado - That is, you cannot traverse an array by having a loop that does - $data = $array[]. Use current - and next instead. + Isto é, você não pode atravessar um array fazendo um loop que contém $data = $array[]. + Ao invés disso use current e next. - Also, $array1[] = $array2 does not - append the values of $array2 to - $array1, but appends - $array2 as the last entry of - $array1. See also multidimensional array - support. + Também, $array1[] = $array2 não adiciona + valores de $array2 à $array1, + mas adiciona $array2 como a última entrada de + $array1. Veja também o suporte ao array multidimensional. - "+" is no longer overloaded as a - concatenation operator for strings, instead it converts it's - arguments to numbers and performs numeric addition. Use - "." instead. + "+" não é mais considerado como um concatenador de + strings, ao invés disso é usado para converter argumentos para números + e executar adições númericas. Use "." para concatenar. - Migration from 2.0: concatenation for strings + Migrando do 2.0: concatenação de strings - In PHP 2.0 this would echo 11, in PHP 3.0 it would - echo 2. Instead use: + No PHP 2.0 isto retornaria echo 11, no PHP 3.0 isto + retornará echo 2. Ao invés disso use: - This would echo 2 in both PHP 2.0 and 3.0. + Isto irá retornar echo 2 em ambas versões do PHP 2.0 e 3.0. - This will echo 11 in PHP 3.0. + Isto retornará echo 11 no PHP 3.0.
diff --git a/appendices/migration4.xml b/appendices/migration4.xml index 857ace33d8..ab03c989e4 100644 --- a/appendices/migration4.xml +++ b/appendices/migration4.xml @@ -1,43 +1,43 @@ - + - Migrating from PHP 3 to PHP 4 + Migrando do PHP 3 para o PHP 4
- What has changed in PHP 4 + O que mudou no PHP 4 - PHP 4 and the integrated Zend engine have greatly improved PHP's - performance and capabilities, but great care has been taken to - break as little existing code as possible. So migrating your code - from PHP 3 to 4 should be much easier than migrating from - PHP/FI 2 to PHP 3. A lot of existing PHP 3 code should be - ready to run without changes, but you should still know about the - few differences and take care to test your code before switching - versions in production environments. The following should give you - some hints about what to look for. + O PHP 4 e a integração com o engine Zend melhoraram incrivelmente a + performance e potencialidades do PHP, mas foi tomado o cuidado + de deixar o código existente o máximo possível. Sendo assim, migrar seu + código do PHP 3 para PHP 4 é muito mais fácil do que migrar do PHP/FI 2 para PHP 3. + Muitos códigos existentes do PHP 3 podem rodar sem alterações, mas você deverá + ficar atento as diferentaças e ter o cuidado de testar seu código antes de trocar as + versões nos sistemas de produções. O material abaixo deverá dar à + você algumas instruções sobre o que procurar.
- Running PHP 3 and PHP 4 concurrently + Rodando PHP 3 e PHP 4 simultaneamente - Recent operating systems provide the ability to perform - versioning and scoping. This features make it possible to let - PHP 3 and PHP 4 run as concurrent modules in one Apache server. + Os sistemas operacionais atuais fornecem a habilidade de de + executar "versioning" e "scoping". Estas características + tornam possível deixar-mos o PHP 3 e PHP 4 rodando simultaneamente + como módulos em um só servidor Apache. - This feature is known to work on the following platforms: + Esta opção é suportada nas seguintes plataformas: - Linux with recent binutils (binutils 2.9.1.0.25 tested) - Solaris 2.5 or better - FreeBSD (3.2, 4.0 tested) + Linux com os recentes binutils (binutils 2.9.1.0.25 testado) + Solaris 2.5 ou superior + FreeBSD (3.2, 4.0 testado) - To enable it, configure PHP3 and PHP4 to use APXS - (--with-apxs) and the necessary link extensions - (--enable-versioning). Otherwise, all standard installations - instructions apply. For example: + Para habilitar isto, configure seu PHP 3 e PHP 4 usando o APXS + (--with-apxs) e linkar as extensões necessárias (--enable-versioning). + Por outro lado, isto também se aplica para todas as instalações padrões. + Por exemplo:
- Migrating Configuration Files + Migrando os arquivos de configuração - The global configuration file, php3.ini, - has changed its name to &php.ini;. + O arquivo de configuração global, php3.ini, + foi alterado para ete nome &php.ini;. - For the Apache configuration file, there are slightly more - changes. The MIME types recognized by the PHP module have - changed. + Para o arquivo de configuração do Apache, há algumas pequenas + mudanças. Os tipos de MIME reconhecidos pelo módulo do PHP foram + alterados. application/x-httpd-php-source - You can make your configuration files work with both versions - of PHP (depending on which one is currently compiled into the - server), using the following syntax: + Você pode fazer seu arquivo de configuração trabalhar com ambas as + versões do PHP (dependendo de qual compilação está no servidor), + usando a seguinte sintaxe: - In addition, the PHP directive names for Apache have changed. + Além disso, os nomes das diretiva do PHP para o Apache foram alteradas. - Starting with PHP 4.0, there are only four Apache directives - that relate to PHP: + Começando com o PHP 4.0, há quatro diretivas para o Apache relacionadas + ao PHP: - There are two differences between the Admin values and the non admin values: + Há duas diferenças entre os valores do Admin e do não admin: - Admin values (or flags) can only appear in the server-wide apache configuration files (e.g., httpd.conf). - Standard values (or flags) cannot control certain PHP directives, for example - safe mode (if you could override safe mode settings in .htaccess files, it would defeat safe-mode's purpose). In contrast, Admin values can modify the value of any PHP directive. + Os valores Admin (ou os flags) só aparecem no server-wide dos arquivos de configuração + do apache (e.g., httpd.conf). + Os valores padrões (ou os flags) não podem controlar determinadas diretivas do PHP, + por exemplo - safe mode (se você pude-se cancelar as configurações do modo seguro em arquivos .htacces, + isto desativaria o modo-seguro). Em contraste, os valores Admin podem modificar qualquer diretiva do PHP.. - To make the transition process easier, PHP 4 is bundled with scripts that automatically convert your Apache configuration and .htaccess files to work with both PHP 3 and PHP 4. These scripts do NOT convert the mime type lines! You have to convert these yourself. + Para tornar o processo de transição mais fácil, o PHP 4 vem com scripts que convertem automaticamente + suas configurações do Apache e arquivos .htacces para trabalharem com ambos PHP 3 e PHP 4. Estes scripts + NÃO convertem as linhas do tipo MIME! Você terá que converter manualmente. - To convert your Apache configuration files, run the apconf-conv.sh script (available in the scripts/apache/ directory). For example: + Para converter seus arquivos de configuração do Apache, rode o script apconf-conv.sh (distponível no + diretório /scripts/apache). Exemplo: - Your original configuration file will be saved in httpd.conf.orig. + Seu arquivo de configuração original será salve como httpd.conf.orig. - To convert your .htaccess files, run the aphtaccess-conv.sh script (available in the scripts/apache/ directory as well): + Para converter seus arquivos .htaccess, rode o script aphtaccess-conv.sh (disponível no + diretório scripts/apache), exemplo: - Likewise, your old .htaccess files will be saved with an .orig prefix. + Como já foi dito, seus antigos arquivos .htacces serão salvos com o prefixo .orig. - The conversion scripts require awk to be installed. + A conversão dos scripts requer que o awk esteja instalado.
- Parser behavior + Comportamento da Análise - Parsing and execution are now two completely separated steps, no - execution of a files code will happen until the complete file and - everything it requires has completely and successfully been - parsed. + A execução e a análise são agora duas etapas completamente separadas, + nenhuma execução de código de arquivo será acontecerá até que tudo seja + completado e analisado completamente. - One of the new requirements introduced with this split is that - required and included files now have to be syntactically - complete. You can no longer spread the different controlling parts - of a control structure across file boundaries. That is you cannot - start a for or while loop, - an if statement or a switch - block in one file and have the end of loop, - else, endif, - case or break statements in - a different file. + Uma das novas exigências introduzidas com este split é que + arquivos requeridos e incluídos agora tem que estar sintaticamente + completos. Você não pode mais espalhar os em diferentes partes os + controles de estrutura ou espalahar os controles através de arquivos. + Você não pode começar um laço for ou while, + um bloco de instruções if ou switch começando + em um arquivo e terminar o loop, else, endif, + case ou break em um arquivo diferente. - It still perfectly legal to include additional code within loops - or other control structures, only the controlling keywords and - corresponding curly braces {...} have to be - within the same compile unit (file or evaled - string). + Ainda é permitido incluir códigos adicionaisdentro dos laços ou + estruturas de controle, somente os controles chaves e os correspondentes + (....) tem que estar compilados na mesma unidade + (arquivo ou evaled string). - This should not harm to much as spreading code like this should be - considered as very bad style anyway. + Isto não deve prejudicar muito considerando que um código como este + é considerado mal feito de qualquer maneira. - Another thing no longer possible, though rarely seen in PHP 3 - code is returning values from a required file. Returning a value - from an included file is still possible. + Outra coisa que não é mais possível, e que é raramente visto em um código + PHP 3 é o retorno de valores de um requerido arquivo. Retornar valores + de um arquivo incluído ainda é possível.
- Error reporting + Relatório de erros
- Configuration changes + Mudanças na Configuração - With PHP 3 the error reporting level was set as a simple - numeric value formed by summing up the numbers related to - different error levels. Usual values where 15 for reporting all - errors and warnings or 7 for reporting everything but simple - notice messages reporting bad style and things like that. + O relatório de erro do PHP 3 foi ajustado para um simples + valor número formado pela soma de números relacionados aos + diferentes níveis de erro. Valores usuais onde 15 para relatar + todos os erros e mensagens ou 7 para relatar qualquer coisa mas + simples observação ao mal estilo e coisas como esta. - PHP 4 has a larger set of error and warning levels and comes with a - configuration parser that now allows for symbolic constants to be used - for setting the intended behavior. + PHP 4 contém um maior nível de erros e avisos e vem com uma + configuração do parser que agora permite que constantes simbólicas + sejam usadas para para ajustar ao comportamente pretendido. - Error reporting level should now be configured by explicitly - taking away the warning levels you do not want to generate error - messages by x-oring them from the symbolic constant - E_ALL. Sounds complicated? Well, lets say you - want the error reporting system to report all but the simple - style warnings that are categorized by the symbolic constant - E_NOTICE. Then you'll put the following into - your &php.ini;: error_reporting = - E_ALL & ~ ( E_NOTICE ). If you want to suppress - warnings too you add up the appropriate constant within the - braces using the binary or operator '|': - error_reporting= E_ALL & ~ ( E_NOTICE | E_WARNING - ). + O nível do relatório de erro agora pode ser configurado explicitamente + removendo os níveis de advertência que você não quer gerar nas suas + mensagens de erro x-oring da constante simbólica E_ALL. + Parece complicado? Bem, vamos dizer que você quer todas as advertências + categorizadas na constante simbólica E_NOTICE. Então você + deverá colocar o seguinte em seu &php.ini;: error_reporting = + E_ALL & - ( E_NOTICE ). Se você quiser suprir as + advertências você deve adicionar a constante apropriada dentro do + parêntese usando o operador '|': + erro_reporting = E_ALL & ~ ( E_NOTICE | E_WARNING ). - When upgrading code or servers from PHP 3 to PHP 4 you should - check these settings and calls to - error_reporting or you might disable - reporting the new error types, especially E_COMPILE_ERROR. This - may lead to empty documents without any feedback of what happened - or where to look for the problem. + Ao atualizar códigos ou servidores do PHP 3 para PHP 4 você + deve checar as configurações e chamadas ao error_reporting + ou você deve desabilitar os novos tipos de relatório de erro, + especialmente E_COMPILE_ERROR. Isto pode ocasionar a limpeza de + documents sem nenhuma resposta do que ocorreu ou onde procurar + pelo problema. - Using the old values 7 and 15 for setting up error reporting is - a very bad idea as this suppresses some of the newly added error - classes including parse errors. This may lead to very strange - behavior as scripts might no longer work without error messages - showing up anywhere. + Usando valores menores que 7 ou 15 para ajustar o relatório + de erro não é uma boa idéia porque pode suprir algumas das + classes de erros adicionadas no parser de erros. Isto pode causar + um comportamento estranho com os scripts e também não irá + mostrar nenhuma mensagem de erro em nenhum lugar. - This has lead to a lot of unreproducible bug reports in the - past where people reported script engine problems they were not - capable to track down while the &true; case was usually some - missing '}' in a required file that the parser was not able to - report due to a misconfigured error reporting system. + No passa isto causou muitas inconveniências porque as + pessoas relatavam problemas nos scripts e na verdade + não eram capazes de consertar erros comuns, como a falta de + um '}' requerido em um arquivo que era passado e que o + parser não era capaz de reportar um erro que era apenas + um erro de uma falta de configuração no sistema. - So checking your error reporting setup should be the first thing - to do whenever your scripts silently die. The Zend engine can - be considered mature enough nowadays to not cause this kind of - strange behavior. + Então checar a sua configuração do relatório de erros + deve ser a primeira coisa a fazer quando os seus scripts + causam erros silenciosos. O engine da Zend pode ser + considerado maduro o bastante nos dias atuais para não + causar estes tipos de erros estranhos.
- Additional warning messages + Mensagens de advertência adicionais - A lot of existing PHP 3 code uses language constructs that - should be considered as very bad style as this code, while doing - the intended thing now, could easily be broken by changes in - other places. PHP 4 will output a lot of notice messages in - such situations where PHP 3 didn't. The easy fix is to just - turn off E_NOTICE messages, but it is usually a good idea to fix - the code instead. + Muitos códigos PHP 3 existentes usam uma linguagem de estrutura + que pode ser considerado um código mal formatado, o que pode + tornar as coisas fáceis agora, pode facilmente ser quebrado + por mudanças em outros lugares. PHP 4 exibe muitas mensagens + de advertência em situações onde o PHP 3 não o fazia. O jeito + fácil de consertar isto é setar para off as mensagens E_NOTICE, + mas geralmente é sempre bom consertar o código. - The most common case that will now produce notice messages is the - use of unquoted string constants as array indices. Both PHP 3 - and 4 will fall back to interpret these as strings if no - keyword or constant is known by that name, but whenever a - constant by that name had been defined anywhere else in the code - it might break your script. This can even become a security risk - if some intruder manages to redefine string constants in a way - that makes your script give him access rights he wasn't intended - to have. So PHP 4 will now warn you whenever you use unquoted - string constants as for example in - $_SERVER[REQUEST_METHOD]. Changing it - to $_SERVER['REQUEST_METHOD'] will - make the parser happy and greatly improve the style and security - of your code. + O caso mais comum que agora irá produzir mensagens de advertência + é o uso de constantes de strings não quotadas como índices de array. + Ambos PHP 3 e PHP 4 tentarão interpretarar isto como se fosse strings + se nenhuma palavra ou constante for conhecida pelo nome, mas sempre que + uma constante por esse nome for definida em qualquer lugar do código + ela pode causar erros no script. Isto pode se tornar um risco de + segurança se um invasor redefinir as strings constantes à um + caminho que faz o seu script dar as permissões corretas que ele + não deveria ter. Então o PHP 4 agora avisa você sempre que + você usar strings constantes não quotadas por exemplo no + $_SERVER[REQUEST_METHOD]. Altere isto para + $_SERVER['REQUEST_METHOD'] que fará + com que o parser fique feliz e melhorará extremamente o + estilo e segurança do seu código. - Another thing PHP 4 will now tell you about is the use of - uninitialized variables or array elements. + Outra coisa que o PHP 4 agora lhe informa é sobre o uso + de variáveis ou elementos de array não inicializados.
- Initializers + Inicializadores - Static variable and class member initializers only accept scalar - values while in PHP 3 they accepted any valid expression. This - is, once again, due to the split between parsing and execution as - no code has yet been executed when the parser sees the - initializer. + Os inicializadores de variáveis estáticas e membros de classes + aceitam somente valores escalares enquanto no PHP 3 eles aceitavam + qualquer expressão válida. Isto é, mais uma vez, devido ao corte entre + a execução e o parsing como nenhum código executado quando o parser + vê o inicializador. - For classes you should use constructors to initialize member - variables instead. For static variables anything but a simple - static value rarely makes sense anyway. + Para classes você deve usar construtores para inicializar + membros ao invés de variáveis. Para variáveis estáticas + pode-se usar qualquer coisa mas raramente uma simples + variável estátira faz algum sentido.
<literal>empty("0")</literal> - The perhaps most controversial change in behavior has happened to the - behavior of the empty. A String containing - only the character '0' (zero) is now considered empty while it - wasn't in PHP 3. + Talvez a mudança mais controversa no comportamento aconteceu na função + empty. Uma string que contém somente caracteres + ' 0 ' (zero) agora é considerada vazia enquanto no PHP 3 ela não era. - This new behavior makes sense in web applications, with all input - fields returning strings even if numeric input is requested, and - with PHP's capabilities of automatic type conversion. But on the - other had it might break your code in a rather subtle way, - leading to misbehavior that is hard to track down if you do not - know about what to look for. + Estes novos comportamentos fazem sentido em aplicativos web, com todos + aqueles campos retornando strings mesmo se entradas númericas são requisitadas, + e com as capacidades do PHP automaticamente converter os tipos. Mas + por outro lado isto pode gerar problemas no seu código de uma + maneira totalmente pertubadora, conduzindo ao um estranho comportamento + que é duro de consertar se você não souber o que você procura.
- Missing functions + Funções abandonadas - While PHP 4 comes with a lot of new features, functions and - extensions, you may still find some functions from version 3 - missing. A small number of core functions has vanished because - they do not work with the new scheme of splitting parsing and - execution as introduced into 4 with the Zend engine. Other - functions and even complete extensions have become obsolete as - newer functions and extensions serve the same task better and/or - in a more general way. Some functions just simply haven't been - ported yet and finally some functions or extensions may be missing - due to license conflicts. + Enquanto o PHP 4 vem com uma série de novas características, + funções e extensões, você talvez encontre algumas funções da + versão 3 que não existem mais. Um pequeno número de funções + do núcleo desapareceu porque elas não funcionavam com o novo + sistema de execução e parsing introduzido na versão 4 com a + Zend engine. Outras funções e mesmo extensões se tornaram + obsoletas para as novas funções e extensões que servem a + mesma tarefa melhor e/ou de uma maneira geral. Algumas funções + simplesmente não foram portadas ainda e finalmente algumas + funções ou extensões podem ter sido retiradas por conflitos + de licença.
- Functions missing due to conceptual changes + Funções abandonadas devido à mudanças conceptuais - As PHP 4 now separates parsing from execution it is no longer - possible to change the behavior of the parser (now embedded in - the Zend engine) at runtime as parsing already happened by - then. So the function short_tags no longer - exists. You can still change the parsers behavior by setting - appropriate values in the &php.ini; file. + Como o PHP 4 agora separa o parsing da execução não é mais possível + alterar o comportamento do parser (agora embutido na Zend engine) + na hora da execução quando o parsing já aconteceu. Então a função + short_tags não existe mais. Você ainda + pode mudar o comportamento dos parsers setando o valor + propriedade no arquivo &php.ini. - Another feature of PHP 3 that is not a part of PHP 4 is the bundled - debugging interface. There are third-party add-ons for the Zend engine - which add similar functionality. + Outra características do PHP 3 que não faz parte do PHP 4 é + a relação embutida de eliminar erros. Existem add-ons de terceiros + para a Zend engine que adicionam um funcionamento similar.
- Deprecate functions and extensions + Depcritamento de funções e extensões - The Adabas and Solid database extensions are no more. Long live - the unified ODBC extension instead. + As extensões dos banco de dados Adabas e Solid não existem mais. + Ao inés delas foi unificado o ODBC.
- Changed status for <function>unset</function> + Mudança de status para <function>unset</function> - unset, although still available, is - implemented as a language construct rather than a function. + unset, embora ainda disponível, é + implementado como um construtor de linguagem melhor que uma função. - This does not have any consequences on the behavior of - unset, but testing for "unset" using - function_exists will return &false; as it would with - other language constructs that look like functions such as - echo. + Isto não tem nenhumas conseqüências no comportamento < de function>unset, mas testar para "unset" usando < function>function_exists retornará o &false; porque com outras construções da língua que olham como funções tais como < function>echo. + Isto não interfere em nada no comportamento do + unset, mas testar "unset" usando + function_exists retornará &false; + porque com outros construtores de linguagens que observam + funcções tais como o echo. - Another more practical change is that it is no longer possible to - call unset indirectly, that is - $func="unset"; $func($somevar) won't work - anymore. + Uma otura mudança mais prática é que não é mais possível chamar + unset indiretamente, isso é, $func="unset"; $func($algumavar) + não irá mais funcionar.
- PHP 3 extension + Extensões PHP 3 - Extensions written for PHP 3 will not work with PHP 4, neither as binaries - nor at the source level. It is not difficult to port extensions to PHP 4 - if you have access to the original source. A detailed description of the - actual porting process is not part of this text. + Extensões escritas para o PHP 3 não irão funcionar com o PHP 4, + nem como binárias nem no código fonte. Não é difícil portar estas + extensões para o PHP 4 se vcê tiver acesso aos fontes originais. + Uma descrição detalhada do processo de portação não faz parte deste + texto.
- Variable substitution in strings + Substituição de variáveis nas strings - PHP 4 adds a new mechanism to variable substitution in - strings. You can now finally access object member variables and - elements from multidimensional arrays within strings. + O PHP 4 adiciona um novo mecanimos para a substituição + de variáveis em strings. Agora você finalmente pode acessar + as variáveis de um objeto membro e seus elementos de um + array multidimensional dentro de strings. - To do so you have to enclose your variables with curly braces with - the dollar sign immediately following the opening brace: + Para fazer isso você tem que incluir nas suas variáveis chaves + com o símbolo da moeda imediatamente após a chave de abertura: {$...} - To embed the value of an object member variable into a string you - simply write "text {$obj->member} text" while - in PHP 3 you had to use something like "text - ".$obj->member." text". + Para embutir o valor de um objeto membro de uma variável + dentro de uma string simplesmente escreva "texto {$obj->membro} texto" + enquanto no PHP 3 você tinha que usar uma coisa como esta + "texto ".$obj->membro." texto". - This should lead to more readable code, while it may break - existing scripts written for PHP 3. But you can easily check for - this kind of problem by checking for the character combination - {$ in your code and by replacing it with - \{$ with your favorite search-and-replace - tool. - + Isto gera um código mais legível, mas pode gerar problemas + em scripts existentes escritos para o PHP 3. Mas + você pode facilmente char este tipo de problema procurando + por uma combinação de caracteres {$ + no seu código e substituindo eles por + \{$ usando sua ferramenta de + procura-e-substituição favorita. +
Cookies - PHP 3 had the bad habit of setting cookies in the reverse order - of the setcookie calls in your code. PHP 4 - breaks with this habit and creates the cookie header lines in - exactly the same order as you set the cookies in the code. + O PHP 3 tinha um mau hábito de configurar os cookies na ordem + reversa das chamadas setcookie no seu código. + O PHP 4 inibiu este mau hábito e cria as linhas de cabeçalhos + dos cookies exatamente na mesma ordem que você definie no + seu código. - This might break some existing code, but the old behaviour was so - strange to understand that it deserved a change to prevent further - problems in the future. + Isto pode gerar problemas no seu código existente, mas o velho + comportamente era tão estranho de se entender que mereceu + uma mudança para previnir futuros problemas.
- Handling of global variables + Manipulação de variáveis globais - While handling of global variables had the focus on to be easy in - PHP 3 and early versions of PHP 4, the focus has changed to be more - secure. While in PHP 3 the following example worked fine, in PHP 4 it - has to be unset($GLOBALS["id"]);. This is only one issue of global - variable handling. You should always have used $GLOBALS, with - newer versions of PHP 4 you are forced to do so in most cases. - Read more on this subject in the - global references section. + A manipulação de variáveis globais tinha o foco de ser + fácil no PHP 3 e versões posteriores à PHP 4, mas este + foco mudou por medidas de segurança. Enquanto em um + script PHP 3 o exemplo a seguir funciona normalmente, + no PHP 4 tem que se usar unset($GLOBALS["id"]);. Isto + é apenas uma introdução da manipulação de variáveis globais. + Você deverá sempre usar $GLOBALS, com as novas versões + do PHP 4 você é forçado a fazer isto na maioria dos casos. + Leia mais sobre este assunto em . - Migration of global variables + Migração das variáveis globais - + - Extending PHP + Estentendo o PHP - Adding functions to PHP + Adicionando funções ao PHP - Function Prototype + Função Prototype - All functions look like this: + Todas as funções separecem com esta: - Even if your function doesn't take any arguments, this is how it is - called. + Mesmo se sua função não pegar nenhum argumento, é assim + que ela é chamada. + - Function Arguments + Argumentos das funções - Arguments are always of type pval. This type contains a union - which has the actual type of the argument. So, if your function - takes two arguments, you would do something like the following at - the top of your function: + Os argumentos são sempre do tipo pval. Este tipo contém a união + que contém o tipo atual do argumento. Então, se sua função + pegar dois argumentos, você faria algo como a seguir no topo + da sua função: + @@ -41,36 +43,39 @@ if (ARG_COUNT(ht) != 2 || getParameters(ht,2,&arg1,&arg2)==FAILURE) { ]]> - - NOTE: Arguments can be passed either by value or by reference. In - both cases you will need to pass &(pval *) to getParameters. If - you want to check if the n'th parameter was sent to you by - reference or not, you can use the function, - ParameterPassedByReference(ht,n). It will return either 1 or 0. + NOTA: Argumentos podem ser passados pelo valor ou pela referência. + Em ambos os casos você irá precisar passar &(pval *) para + o getParameters. Se você quer checar se n'th foi + enviado por referência ou não, você pode usar a seguinte função. + ParameterPassedByReference(ht,n). Isto irá retornar 1 ou 0. + + - When you change any of the passed parameters, whether they are - sent by reference or by value, you can either start over with the - parameter by calling pval_destructor on it, or if it's an ARRAY - you want to add to, you can use functions similar to the ones in - internal_functions.h which manipulate return_value as an ARRAY. + Quando você muda qualquer argumento passado por referência, + se eles foram emitidos por referência ou pelo valor, você + pode começar a partir do parâmetro chamado pela pval_destructor, + ou se for um ARRAY que você quer adicionar, você pode usar + funções similares às do arquivo internal_functions.h que + manipula o return_value como um ARRAY. - Also if you change a parameter to IS_STRING make sure you first - assign the new estrdup()'ed string and the string length, and only - later change the type to IS_STRING. If you change the string of a - parameter which already IS_STRING or IS_ARRAY you should run - pval_destructor on it first. + Também se você mudar um parâmetro para IS_STRING tenha + certeza de primeiro atribuir a string e o tamanho dela ao + estrdup()'ed, e somente mais tarde alterar o tipo para + IS_STRING. Se você quiser alterar a string de um parâmetro + que já é IS_STRING ou IS_ARRAY você deve rodar o pval_destructor + primeiro. - Variable Function Arguments + Argumentos das Variáveis de Funções - A function can take a variable number of arguments. If your function can - take either 2 or 3 arguments, use the following: + Uma função pode pegar um número de variáveis e argumentos. Se sua + função precisa pegar 2 ou 3 argumentos, use as instruções a seguir: - Variable function arguments + Argumentos das Variáveis de Funções 3 || - Using the Function Arguments + Usando os Argumentos das Funções - The type of each argument is stored in the pval type field. This - type can be any of the following: + O tipo de cada argumento é armazenado no campo do tipo pval. + Este tipo pode ser qualquer um dos seguintes: - PHP Internal Types + Tipos Internos do PHP @@ -104,7 +109,7 @@ if (arg_count < 2 || arg_count > 3 || IS_LONG - Long integer + Inteiro longo IS_ARRAY @@ -112,7 +117,7 @@ if (arg_count < 2 || arg_count > 3 || IS_EMPTY - None + Nenhum(a) IS_USER_FUNCTION @@ -120,7 +125,7 @@ if (arg_count < 2 || arg_count > 3 || IS_INTERNAL_FUNCTION - ?? (if some of these cannot be passed to a function - delete) + ?? (se alguma dessas não puder ser passada para uma função - delete) IS_CLASS @@ -135,10 +140,10 @@ if (arg_count < 2 || arg_count > 3 ||
- If you get an argument of one type and would like to use it as - another, or if you just want to force the argument to be of a - certain type, you can use one of the following conversion - functions: + Se você pegar um argumento de um tipo e quiser usar ele + como outro tipo, ou se você somente quer forçar o argumento + a ser de um certo tipo, você pode usar as seguintes funções + para conversão: - These function all do in-place conversion. They do not return anything. + Estas funções fazem conversões in-place. Elas não retornam nada. - The actual argument is stored in a union; the members are: + O argumento atual é armazenado na união; os membros são: IS_STRING: arg1->value.str.val IS_LONG: arg1->value.lval @@ -162,45 +167,47 @@ convert_string_to_number(arg1); /* Converts string to either LONG or DOUBLE dep
- Memory Management in Functions + Gerenciamento de Memória nas Funções - Any memory needed by a function should be allocated with either - emalloc() or estrdup(). These are memory handling abstraction - functions that look and smell like the normal malloc() and - strdup() functions. Memory should be freed with efree(). + Toda memórai necessária para uma função deve ser alocada no + emalloc() ou estrdup(). Estes eventos de memória são abstratos + e se parecem com as funções normais como a malloc() e strdup(). + A memória deve ser liberada com efree(). - There are two kinds of memory in this program: memory which is - returned to the parser in a variable, and memory which you need for - temporary storage in your internal function. When you assign a - string to a variable which is returned to the parser you need to - make sure you first allocate the memory with either emalloc() or - estrdup(). This memory should NEVER be freed by you, unless you - later in the same function overwrite your original assignment - (this kind of programming practice is not good though). + Há dois tipos de memória neste programa: a memória que é + retornada para o parser em uma variável, e a memória que é + temporariamente armazenada na sua função interna. Quando + você atribui uma string a uma variável que é retornada ao + parser você preicsa ter certeza de primeiro alocar a memória + com o emalloc() ou estrdup(). Esta memória não DEVE ser + liberada por você, a menos que uma mesma função sobreescreva + a função original (esta prática de programação + não é muito boa). - For any temporary/permanent memory you need in your - functions/library you should use the three emalloc(), estrdup(), - and efree() functions. They behave EXACTLY like their counterpart - functions. Anything you emalloc() or estrdup() you have to efree() - at some point or another, unless it's supposed to stick around - until the end of the program; otherwise, there will be a memory - leak. The meaning of "the functions behave exactly like their - counterparts" is: if you efree() something which was not - emalloc()'ed nor estrdup()'ed you might get a segmentation - fault. So please take care and free all of your wasted memory. + Para toda memória temporária/permanente que você necessitar + usar em suas funções você deve usar as três funções + emalloc(), estrdup(), e efree(). Elas comportam-se EXATAMENTE + como suas funções contrapartes. Para qualquer uso da emalloc() ou estrdup() + você deve usar efree() em algum ponto ou outro, a menos que ela + precise ficar até o fim do programa; se não, haverá um escape de memória. + O significado de "as funções comportam-se exatamente como suas contrapartes" + é: se você usa efree() em algo que não era emalloc()'ed ou estrdup()'ed + você deve começar uma falha na segmentação. Então por favor tome cuidado e + libere toda sua memória desperdiçada. - If you compile with "-DDEBUG", PHP will print out a list of all - memory that was allocated using emalloc() and estrdup() but never - freed with efree() when it is done running the specified script. + Se você compilar com "-DDEBUG", o PHP irá imprimir uma lsita + de toda memória que foi alocada e usada com o emalloc() e estrdup() + mas nunca foi liberda com o efree() quando ele acabar de rodar um + script especificado. - Setting Variables in the Symbol Table + Setando Variáveis na Tabela de Símbolos - A number of macros are available which make it easier to set a - variable in the symbol table: + Um número de macros está disponível para tornar fácil o trabalho + de setar uma variável na tabela de símbolos: SET_VAR_STRING(name,value) @@ -211,29 +218,30 @@ convert_string_to_number(arg1); /* Converts string to either LONG or DOUBLE dep - Be careful with SET_VAR_STRING. The value part must be malloc'ed - manually because the memory management code will try to free this - pointer later. Do not pass statically allocated memory into a - SET_VAR_STRING. + Tenha cuidado com a SET_VAR_STRING. Parte do valor deve ser + malloc'ed manualmente porque o código do gerenciador de memória + irá tentar lbierar este ponteiro mais tarde. Não passe + memória estática alocada na SET_VAR_STRING. - Symbol tables in PHP are implemented as hash tables. At any - given time, &symbol_table is a pointer to the 'main' symbol - table, and active_symbol_table points to the currently active - symbol table (these may be identical like in startup, or - different, if you're inside a function). + A tabela de símbolos no PHP é implementada como uma tabela de misutra. + A toda hora, &symbol_table é apontado para o 'principal' + símbolo da tabela, e active_symbol_table aponta para o + símbolo corrente da tabela (isto pode ser identificado no + início, ou diferente, se você estiver dentro da função). - The following examples use 'active_symbol_table'. You should - replace it with &symbol_table if you specifically want to work - with the 'main' symbol table. Also, the same functions may be - applied to arrays, as explained below. + O exemplo a seguir usa o 'active_symbol_table'. Você + deve substituir isto por &symbol_table se você + quer especificamente trabalhar com a tabela de símbolos + 'principal'. Também, as mesmas funções se apliquem à + arrays, como explicado a seguir. - Checking whether $foo exists in a symbol table + Checando se $foo existe na tabela de símbolos - Finding a variable's size in a symbol table + Procurando o tamanho de uma variável em uma tabela de símbolos - Arrays in PHP are implemented using the same hashtables as - symbol tables. This means the two above functions can also be - used to check variables inside arrays. + Os arrays no PHP são executadas usando as mesmas hashtables + que as tabelas de símbolos. Isto significa que as duas + funções abaixo também podem ser usadas para checar + variáveis dentro de arrays. - If you want to define a new array in a symbol table, you should do - the following. + Se você quiser definir um novo array numa tabela de símbolos, + você deve fazer o seguinte. + - First, you may want to check whether it exists and abort - appropriately, using hash_exists() or hash_find(). + Primeiro, você talvez queria checar se já não existe um array + e abortá-lo se houver, usando o hash_exists() ou hash_find(). + - Next, initialize the array: + Após, inicialize o array: - Initializing a new array + Inicializando um novo array - This code declares a new array, named $foo, in the active symbol - table. This array is empty. + Este código declara um novo array, chamado $foo, na tabela + de símbolos ativa. Este array está vazio. - Here's how to add new entries to it: + Aqui está o código apra adicionar novas entrads à ele: - Adding entries to a new array + Adicionando novas entradas ao array - - If you'd like to modify a value that you inserted to a hash, you - must first retrieve it from the hash. To prevent that overhead, - you can supply a pval ** to the hash add function, and it'll be - updated with the pval * address of the inserted element inside the - hash. If that value is &null; (like in all of the above examples) - - that parameter is ignored. + + Se você quiser modificar o valor que foi inserido ao hash, você + deve primeiro pegá-lo do hash. Para previnir overhead, você pode + suprir a pval ** da função adicionar do hash, e isto irá + atualizar com o endereço pval * do elemento inserido dentro + do hash. Se o valor for &null; (como em todos os exemplos abaixo) - + aquele parâmetro é ignorado. - hash_next_index_insert() uses more or less the same logic as - "$foo[] = bar;" in PHP 2.0. + hash_next_index_insert() usa mais ou menos a mesma lógica que + "$foo[] = bar;" do PHP 2.0. - If you are building an array to return from a function, you can - initialize the array just like above by doing: + Se você está construindo um array que retorna de uma função, + você pode inicializar o array como no exemplo abaixo: - ...and then adding values with the helper functions: + ...e então adicionar valores com as funções do helper: - Of course, if the adding isn't done right after the array - initialization, you'd probably have to look for the array first: + Claro, se a adição não terminou corretamente depois da + inicialização do array, você provavelmente deverá + procurar pelo array primeiro: value.ht... } - Note that hash_find receives a pointer to a pval pointer, and not - a pval pointer. + Note que o hash_find recebe o ponteiro para um ponteiro pval, e + não um ponteiro pval. - Just about any hash function returns SUCCESS or FAILURE (except - for hash_exists(), which returns a boolean truth value). + Assim como qualquer função hash retorna SUCESSO ou FALHA (exceto + para o hash_exists(), que retorna um valor booleano verdadeiro). - Returning simple values + Retornando valores simples - A number of macros are available to make returning values from a - function easier. + Um número de macros estão disponíveis para fazer o retorno de + valores de uma função ser muito mais fácil. - The RETURN_* macros all set the return value and return from the - function: + A macro RETURN_* ajusta todos os valores de retorno e do retorno + da função: RETURN RETURN_FALSE @@ -394,33 +406,34 @@ else { use arr->value.ht... } - The string macros above will all estrdup() the passed 's' - argument, so you can safely free the argument after calling the - macro, or alternatively use statically allocated memory. + As macros de string abaixo serão todas estrdup() passadas para + 's' argumento, então você pode seguramente liberar o argumento + após chamar a macro, ou alternativamente usar uma memória + estática alocada. - If your function returns boolean success/error responses, always - use RETURN_TRUE and RETURN_FALSE respectively. + Se sua função retornar respostas booleanas de sucesso/erro, + sempre use RETURN_TRUE e RETURN_FALSE respectivamente. - Returning complex values + Retornando valores complexos - Your function can also return a complex data type such as an - object or an array. + Sua função pode também retornar um tipo de dado complexo assim + como um objeto ou um array. - Returning an object: + Retornando um objeto: - Call object_init(return_value). - Fill it up with values. The functions available - for this purpose are listed below. - Possibly, register functions for this object. - In order to obtain values from the object, the function would - have to fetch "this" from the active_symbol_table. Its type - should be IS_OBJECT, and it's basically a regular hash table - (i.e., you can use regular hash functions on .value.ht). The - actual registration of the function can be done using: + Chamar o object_init(return_value). + Preencher isto com valores. A função + disponível para este propósito é listada a seguir. + Possivelmente, registrar a função para este objeto. + A fim de obter os valores do objeto, a função + teria que buscar "this" do active_symbol_table. Este + tipo deverá ser IS_OBJECT, e é basicamente uma tabela + hash regular (i.e., você pode usar funções hash nos .value.ht). + O registrador atual da função pode ser usado fazendo: - The functions used to populate an object are: + As funções usadas para povoar um objeto: add_property_long( return_value, property_name, l ) - Add a property named 'property_name', of @@ -444,16 +457,16 @@ add_method( return_value, function_name, function_ptr ); - Returning an array: + Retornando um array: - Call array_init(return_value). - Fill it up with values. The functions available - for this purpose are listed below. + Chamar array_init(return_value). + Preencher isto com valores. A função disponível + para este propósito é listada a seguir. - The functions used to populate an array are: + As funções usadas para povoar um array são: add_assoc_long(return_value,key,l) - add associative entry with key 'key' and long value 'l' @@ -476,13 +489,13 @@ add_method( return_value, function_name, function_ptr ); - Using the resource list + Usando a lista de recursos - PHP has a standard way of dealing with various types of - resources. This replaces all of the local linked lists in PHP 2.0. + O PHP tem uma maneira padrão de trator os vários tipos de + recursos. Isto substitui todos os local linked lists do PHP 2.0. - Available functions: + Funções disponíveis: php3_list_insert(ptr, type) - returns the 'id' @@ -494,16 +507,16 @@ add_method( return_value, function_name, function_ptr ); updates 'type' to the resource's type - Typically, these functions are used for SQL drivers but they can - be used for anything else; for instance, maintaining file - descriptors. + Tipicamente, estas funções são usadas para drivers SQL mas + elas podem ser usadas para qualquer otura coisa; para instanciar, + manusear arquivos de descritores. - Typical list code would look like this: + Um código típico é listado a seguir: - Adding a new resource + Adicionando novos recursos type = IS_LONG; - Using an existing resource + Usando um recurso existente - Deleting an existing resource + Deletando um recurso existente value.lval); ]]> - - The resource types should be registered in php3_list.h, in enum - list_entry_type. In addition, one should add shutdown code for - any new resource type defined, in list.c's list_entry_destructor() - (even if you don't have anything to do on shutdown, you must add - an empty case). + + O tipo de recurso deve ser registrado no php3_list.h, no enum + list_entry_type. Além disso, um deve adicionar código para + qualquer novo tipo de recurso definido, em list.c's list_entry_destructor() + (mesmo se você não tem nada para adicionar ao shutdown, você + deve adicionar um caso em branco). - Using the persistent resource table + Usando o recurso persistente da tabela - PHP has a standard way of storing persistent resources (i.e., - resources that are kept in between hits). The first module to use - this feature was the MySQL module, and mSQL followed it, so one - can get the general impression of how a persistent resource should - be used by reading mysql.c. The functions you should look at are: + O PHP tem uma maneira padrão de armazenar recursos persistentes (i.e., + recursos que são mantidos dentre os hits). O primeiro módulo à usar + esta característica foi o módulo MySQL, e mSQL seguindo-os, então + um pode pegar uma impressão geral de como um recurso persistente + deve ser usado lendo mysql.c. As funções devem se parecem com as abaixo: php3_mysql_do_connect @@ -571,33 +584,31 @@ php3_list_delete(resource_id->value.lval); - The general idea of persistence modules is this: + A idéia geral dos módulos persistentes é esta: - Code all of your module to work with the - regular resource list mentioned in section (9). - Code extra connect functions that check if the - resource already exists in the persistent resource list. If it - does, register it as in the regular resource list as a pointer to - the persistent resource list (because of 1., the rest of the code - should work immediately). If it doesn't, then create it, add it - to the persistent resource list AND add a pointer to it from the - regular resource list, so all of the code would work since it's - in the regular resource list, but on the next connect, the - resource would be found in the persistent resource list and be - used without having to recreate it. You should register these - resources with a different type (e.g. LE_MYSQL_LINK for - non-persistent link and LE_MYSQL_PLINK for a persistent link). + Codifique todos os seus módulos para trabalhar + com um recurso regular mecionados na seção (9). + Codifique funções extras de conexão para checar + se o recurso já existe na lista de recursos persistentes. Se já + existir, registre ela na lista de recursos regular como um ponteiro + para a lista de recursos persistentes (porque o 1., o resto do código + deverá funcionar imediatamente). Se ela não existe, então crie ela, adicione-a + a lista de recursos persistentes E adicione um ponteiro para ela vindo da + lista de recursos regular, mas na próxima conexão, o recurso + será encontrado na lsita de recursos persitentes e será usado + sem ter que recriá-lo. Você deve registrar estes recursos + com um tipo diferente (e.g. LE_MYSQL_LINK para link + não-persistente e LE_MYSQL_PLINK para um link persistente). - If you read mysql.c, you'll notice that except for the more - complex connect function, nothing in the rest of the module has to - be changed. + Se você ler o mysql.c, você irá notar que exceto pela função + complexa de conexão, nada no resto do módulo tem que ser mudado. - The very same interface exists for the regular resource list and - the persistent resource list, only 'list' is replaced with - 'plist': + A mesma relação existe para a lista de recursos regular e + para a lista de recursos persistentes, somente a 'list' é + substituída com 'plist': php3_plist_insert(ptr, type) - returns the 'id' @@ -610,284 +621,295 @@ php3_list_delete(resource_id->value.lval); - However, it's more than likely that these functions would prove to - be useless for you when trying to implement a persistent module. - Typically, one would want to use the fact that the persistent - resource list is really a hash table. For instance, in the - MySQL/mSQL modules, when there's a pconnect() call (persistent - connect), the function builds a string out of the host/user/passwd - that were passed to the function, and hashes the SQL link with - this string as a key. The next time someone calls a pconnect() - with the same host/user/passwd, the same key would be generated, - and the function would find the SQL link in the persistent list. + Entretanto, é mais provável que estas funções provariam ser + inútils a não quando você tenta implementar um módulo persistente. + Tipicamente, um seria usada de fato para a lista de recursos + persistentes que realmente seria uma tabela hash. Para instanciar, + nos módulos de conexão MySQL/mSQL, quando existe uma chamada + pconnect() (conexão persistente), a função constrói uma string fora + do host/usr/passwd que são passadas para a função, e mistura o link + SQL com esta string como uma chave. Na próxima vez que alguém + chamar a pconnect() com os mesmos host/user/passwd, a mesma chave + deverá ser gerada, e a função encontraria o link SQL na + lista persistente. - Until further documented, you should look at mysql.c or msql.c to - see how one should use the plist's hash table abilities. + Até que seja feita documentação adicional, você deve olhar no + mysql.c ou msql.c para ver como deve usar as habilidades da + plist's tabela de hash. - One important thing to note: resources going into the persistent - resource list must *NOT* be allocated with PHP's memory manager, - i.e., they should NOT be created with emalloc(), estrdup(), etc. - Rather, one should use the regular malloc(), strdup(), etc. The - reason for this is simple - at the end of the request (end of the - hit), every memory chunk that was allocated using PHP's memory - manager is deleted. Since the persistent list isn't supposed to - be erased at the end of a request, one mustn't use PHP's memory - manager for allocating resources that go to it. + Uma coisa importante a notar: recursos que vão para para a lista + de recursos persistentes *NÃO" devem ser alocados no gerenciador + de memória do PHP, i.e., NÃO devem ser criados com emalloc(), strdup(), etc. + O motivo para isto é simples - ao fim da requisição (fim do hit), + cada pedaço de memória que foi alocada usando o gerenciador + de memória do PHP é deletado. Desde que a lista persistente + não é supostamente para ser deletada ao fim da requisição, + não se deve usar o gerenciador de memória do PHP + para alocar recursos que vão para ela. - When you register a resource that's going to be in the persistent - list, you should add destructors to it both in the non-persistent - list and in the persistent list. The destructor in the - non-persistent list destructor shouldn't do anything. The one in - the persistent list destructor should properly free any resources - obtained by that type (e.g. memory, SQL links, etc). Just like - with the non-persistent resources, you *MUST* add destructors for - every resource, even it requires no destruction and the - destructor would be empty. Remember, since emalloc() and friends - aren't to be used in conjunction with the persistent list, you - mustn't use efree() here either. + Quando você registra um recurso que vai ficar na lista persistente, + você deve adicionar desconstrutores em ambas as listas persistente + e não-persistente. O desconstrutor na lista não-persistente + não deve fazer nada. Já o que está na lista persistente + deve liberar corretamente qualquer recurso obtido por este + tipo (e.g. memória, SQL links, etc). Assim como os recursos da lista + não-persistente, você *DEVE* adicionar desconstrutores para + qualquer recurso, mesmo os que não requerem desconstrutores + e este desconstrutor ficaria vazio. Lembre-se, desde que + emalloc() e seus amigos não estão sendo usados em conjunto + com a lista persistente, você não deve usar o efree(). - Adding runtime configuration directives + Adicionar diretivas de configuração runtime - Many of the features of PHP can be configured at runtime. These - configuration directives can appear in either the designated - php3.ini file, or in the case of the Apache module version in the - Apache .conf files. The advantage of having them in the Apache - .conf files is that they can be configured on a per-directory - basis. This means that one directory may have a certain - safemodeexecdir for example, while another directory may have - another. This configuration granularity is especially handy when - a server supports multiple virtual hosts. + Muitas características do PHP podem ser configuradas em modo runtime. + Estas diretivas de configurações podem aparecer no arquivo de + configuração php3.ini, ou no caso na versão do módul para o Apache + nos arquivos .conf do Apache. A vantagem de tê-las nos arquivos + .conf do Apache é que elas podem ser configuradas em apenas + um diretório. Isto significa que um diretório pode ter um certo + safemodeexecdir por exemplo, enquanto em outro diretório + pode ter um outro tipo de safemodeexecdir. Estas configurações + são especiamente acessíveis quando um servidor suporta + múltiplos hosts virtuais. - The steps required to add a new directive: + Os requisitos para adicionar uma diretiva: - Add directive to php3_ini_structure struct in mod_php3.h. + Adicione a diretiva php3_ini_structure struct em mod_php3.h. - In main.c, edit the php3_module_startup - function and add the appropriate cfg_get_string() or - cfg_get_long() call. + No main.c, edite a função php3_module_startup + e adicione a chamada apropriada cfg_get_string() ou + cfg_get_long(). - Add the directive, restrictions and a comment - to the php3_commands structure in mod_php3.c. Note the - restrictions part. RSRC_CONF are directives that can only be - present in the actual Apache .conf files. Any OR_OPTIONS - directives can be present anywhere, include normal .htaccess - files. + Adicione a diretiva, restrições e comentários + à estrutura de php3_commands em mod_php3.c. Anote as partes + restritras. RSRC_CONF são diretivas que somente estão presentes + nos arquivos .conf do Apache. Qualquer + diretiva OR_OPTIONS pode estar presente em qualquer lugar, + incluindo os arquivos .htaccess. - In either php3take1handler() or - php3flaghandler() add the appropriate entry for your directive. + Em php3takelhandler() ou php3flaghandler() + adicione a entrada apropriada para sua diretiva. - In the configuration section of the - _php3_info() function in functions/info.c you need to add your - new directive. + Na seção de configuração da função + _php3_info() em functions/info.c você precisa adicionar + sua nova diretiva. - And last, you of course have to use your new - directive somewhere. It will be addressable as - php3_ini.directive. + E por último, você naturalmente tem que + usar sua nova diretiva em algum lugar. Ela será + endereçada como php3_ini.directive. - Calling User Functions + Chamando Funções do Usuário - To call user functions from an internal function, you should use - the call_user_function function. + Para chamar funções do usuário de uma função interna, você + deve usar a função call_user_function. - call_user_function returns SUCCESS on success, - and FAILURE in case the function cannot be found. You should check - that return value! If it returns SUCCESS, you are responsible for - destroying the retval pval yourself (or return it as the return value - of your function). If it returns FAILURE, the value of retval is - undefined, and you mustn't touch it. + call_user_function retorna SUCESSO no sucesso, + e FALHA no caso de a função não ter sido encontrada. + Você deve checar este valor de retorno! Se ela retornar SUCESSO, + você é responsável por destruir a retval pval por você mesmo + (ou retornar ela como um valor de retorno da sua função). + Se ela retornar FALHA, o valor da retval é indefinido, + e você não deve mexe nisto. - All internal functions that call user functions - must be reentrant. Among other things, this - means they must not use globals or static variables. + Todas as funções internas que chama funções + de usuário devem ser reentrantes. + Entre outras coisas, isto significa que ela não deve + usar variáveis globais ou estáticas. - call_user_function takes six arguments: + call_user_function usa seis argumentos: HashTable *function_table - This is the hash table in which the function is to be looked up. + Esta é a tabela hash onde a função deve ser procurada. pval *object - This is a pointer to an object on which the function is invoked. - This should be &null; if a global function is called. If it's not - &null; (i.e. it points to an object), the function_table argument is - ignored, and instead taken from the object's hash. The object *may* - be modified by the function that is invoked on it (that function - will have access to it via $this). If for some reason you don't - want that to happen, send a copy of the object instead. + Este é o ponteiro para um objeto em que a função é invocada. + Ele dever &null; se a função global é chamada. E se ele + não é &null; (i.e. este ponteio é um objeto), o argumento + function_table é ignorado, ao invés de pegar o hash do objeto. + O objeto *talvez* seja modificado pela função que é invocada + nele (esta função talvez tenha acesso a ele via $this). + Se por alguma razão você não quer que isto aconteça, + envie uma cópia do objeto ao invés dele. pval *function_name - The name of the function to call. Must be a pval of type - IS_STRING with function_name.str.val and function_name.str.len - set to the appropriate values. The function_name is modified by - call_user_function() - it's converted to lowercase. If you need to - preserve the case, send a copy of the function name instead. + O nome da função à ser chamada. Deve ser um pval do tipo + IS_STRING com function_name.str.val e function_name.str.len + enviando os valores apropriados. A function_name é modificada + por call_user_function() - que é convertido para letra minúscula. + Se você precisa preservar caso, envie uma cópia do + nome da função ao invés dela. pval *retval - A pointer to a pval structure, into which the return value of - the invoked function is saved. The structure must be previously - allocated - call_user_function does NOT allocate - it by itself. + Um ponteiro para uma estrutura do pval, onde o valor + retornada do a função invocada é salvo. A estrutura deve + previamente alocada - call_user_function + NÃO aloque por você mesmo. int param_count - The number of parameters being passed to the function. + O número de parâmetros passados à função. pval *params[] - An array of pointers to values that will be passed as arguments to the - function, the first argument being in offset 0, the second in offset - 1, etc. The array is an array of pointers to pval's; The pointers - are sent as-is to the function, which means if the function modifies - its arguments, the original values are changed (passing by reference). - If you don't want that behavior, pass a copy instead. + Um array de ponteiros para valores que vão ser passados + como argumentos para a função, o primeiro argumento começa no + offset 0, o segundo no offset 1, etc. O array é um array + de ponteiros para pval's; Os ponteiros são + enviados como-são para a função, isto significa que se a função + é modificada por seus argumentos, os valores originais são + alterados (passando por referência). + Se você não quer este comportamento, passe uma cópia ao + invés do original. - Reporting Errors + Relatando erros - To report errors from an internal function, you should call the - php3_error function. This takes at least two - parameters -- the first is the level of the error, the second is - the format string for the error message (as in a standard - printf call), and any following arguments - are the parameters for the format string. The error levels are: + Para relatar erros de uma função interna, você deve chamar a + função php3_error. Ela pega ao menos + dois parâmetros -- o primeiro é o nível do erro, o segundo + é a string formatada para a mensagem de erro (como em uma + chamada padrão printf), e os argumentos + seguintes são os parâmetros para a string formatada. Os níveis + de erro são: E_NOTICE - Notices are not printed by default, and indicate that the script - encountered something that could indicate an error, but could also - happen in the normal course of running a script. For example, - trying to access the value of a variable which has not been set, - or calling stat on a file that doesn't exist. + Avisos não são mostrados por padrão, e indicam que o script + encontrou algo que poderia indicar um erro, mas que pode + também ter acontecido na execução do script. Por exemplo, + tentando acessar um valor de uma variável que não foi setada, + ou chamando stat em um arquivo que não existe. E_WARNING - Warnings are printed by default, but do not interrupt script - execution. These indicate a problem that should have been trapped - by the script before the call was made. For example, calling - ereg with an invalid regular expression. + Os avisos são mostrados por padrão, mas não interrompem a + execução do script. Eles indicam um problema que deve ter + acontecido antes do script ser chamado. Por exemplo, + chamando ereg com uma expressão regular inválida. E_ERROR - Errors are also printed by default, and execution of the script is - halted after the function returns. These indicate errors that can - not be recovered from, such as a memory allocation problem. + Os erros também são mostrados por padrão, e a execução do script é + interrompida após a função retornar. Ele indica erros que podem + não ser recuperados, como um problema de alocação de memória. E_PARSE - Parse errors should only be generated by the parser. The code is - listed here only for the sake of completeness. + Erros do Parse deveriam unicamente ser gerados somente pelo parser. O código é + listado aqui somente para a causa de integridade. E_CORE_ERROR - This is like an E_ERROR, except it is generated by the core - of PHP. Functions should not generate this type of error. + Este é como um E_ERROR, exceto que ele é gerado pelo núcleo + do PHP. Funções não devem gerar este tipo de erro. E_CORE_WARNING - This is like an E_WARNING, except it is generated by the core - of PHP. Functions should not generate this type of error. + Este é como um E_WARNING, exceto que ele é gerado pelo núcleo + do PHP. Funções não devem gerar este tipo de erro. E_COMPILE_ERROR - This is like an E_ERROR, except it is generated by the Zend Scripting - Engine. Functions should not generate this type of error. + Este é como um E_ERROR, exceto que ele é gerado pelo Zend Scripting + Engine. Funções não devem gerar este tipo de erro. E_COMPILE_WARNING - This is like an E_WARNING, except it is generated by the Zend Scripting - Engine. Functions should not generate this type of error. + Este é como um E_WARNING, exceto que ele é gerado pelo Zend Scripting + Engine. Funções não devem gerar este tipo de erro. E_USER_ERROR - This is like an E_ERROR, except it is generated in PHP code by using - the PHP function trigger_error. Functions should - not generate this type of error. + Este é como um E_ERROR, exceto que ele é gerado no código PHP + usando a função PHP trigger_error. + Funções não devem gerar este tipo de erro. E_USER_WARNING - This is like an E_WARNING, except it is generated by using the PHP - function trigger_error. Functions should not - generate this type of error. + Este é como um E_WARNING, exceto que ele é gerado no código PHP + usando a função PHP trigger_error. + Funções não devem gerar este tipo de erro. E_USER_NOTICE - This is like an E_NOTICE, except it is generated by using the PHP - function trigger_error. Functions should not - generate this type of error. + Este é como um E_NOTICE, exceto que ele é gerado no código PHP + usando a função PHP trigger_error. + Funções não devem gerar este tipo de erro. E_ALL - All of the above. Using this error_reporting level will show - all error types. + Todos acima. Usando este nível de error_reporting você + verá todos os tipos de erros. diff --git a/appendices/reserved.constants.core.xml b/appendices/reserved.constants.core.xml index 57b2a132fd..ce697e9094 100644 --- a/appendices/reserved.constants.core.xml +++ b/appendices/reserved.constants.core.xml @@ -1,15 +1,15 @@ - + - Core Predefined Constants - Constants defined in the PHP core, Zend, and SAPI modules + Constantes Pré-definidas do Núcleo + Constantes definidas no núcleo do PHP, Zend, e módulos SAPI - Description + Descrição - These constants are defined by the PHP core. This includes PHP, - the Zend engine, and SAPI modules. + Estas constantes são definidas pelo núcleo do PHP. Isto + inclui o PHP, a Zend engine, e os módulos SAPI. diff --git a/appendices/reserved.constants.standard.xml b/appendices/reserved.constants.standard.xml index 665125912d..751594edca 100644 --- a/appendices/reserved.constants.standard.xml +++ b/appendices/reserved.constants.standard.xml @@ -1,5 +1,5 @@ - + - Standard Predefined Constants - Constants defined in PHP by default + Constantes Padrões Pré-definidas + Constantes definidas no PHP por padrão - Description + Descrição - These constants are defined in PHP by default. + Estas constantes são definidas por padrão no PHP. diff --git a/appendices/resources.xml b/appendices/resources.xml index 92271dc16c..5a7e9b05ea 100755 --- a/appendices/resources.xml +++ b/appendices/resources.xml @@ -1,23 +1,23 @@ - + - List of Resource Types + Lsita de Tipos de Recursos - The following is a list of functions which create, use or destroy - PHP resources. The function is_resource can be - used to determine if a variable is a resource and - get_resource_type will return the type of - resource it is. + A seguir há uma lista de funções que criam, usam e destróem + recursos do PHP. A função is_resource podem + ser usadas para determinar se a variável é um recurso e + o get_resource_type irá retornar o tipo + de recurso que está sendo usado. - Resource Types + Tipos de Recursos - Resource Type Name - Created By - Used By - Destroyed By - Definition + Nome do Tipo de Recurso + Criado por + Usado por + Destroído por + Definição diff --git a/appendices/tokens.xml b/appendices/tokens.xml index d8995d9072..c8291dd5ca 100644 --- a/appendices/tokens.xml +++ b/appendices/tokens.xml @@ -1,17 +1,18 @@ - + - List of Parser Tokens + Lista dos Símbolos od Parse - Various parts of the PHP language are represented internally by types like - T_SR. PHP outputs identifiers like this one in parse errors, like - "Parse error: unexpected T_SR, expecting ',' or ';' in script.php on line 10." + Várias partes da linguagem PHP são representadas internamente por + tipos como T_SR. Como estas saídas de identificadores do PHP nos + erros do parse, como "Parse error: unexpected T_SR, expecting ',' or ';' in + script.php on line 10." - You're supposed to know what T_SR means. For everybody who doesn't - know that, here is a table with those identifiers, PHP-syntax and - references to the appropriate places in the manual. + Você supostamente já deve sar o que T_SR significa. Para quem + não sabe, aqui vai uma tabela de seus identificadores, sintaxe-PHP + e as referências apropriadas colocadas no manual.
Tokens