mirror of
https://github.com/sigmasternchen/php-doc-en
synced 2025-03-15 16:38:54 +00:00
fixing
git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@105025 c90b9560-bf6c-de11-be94-00142212c4b1
This commit is contained in:
parent
cffa746463
commit
6b5c3112dd
8 changed files with 736 additions and 755 deletions
|
@ -1,5 +1,5 @@
|
|||
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||
<!-- $Revision: 1.22 $ -->
|
||||
<!-- $Revision: 1.23 $ -->
|
||||
<appendix id="aliases">
|
||||
<title>List of Function Aliases</title>
|
||||
<para>
|
||||
|
@ -14,8 +14,7 @@
|
|||
<function>is_integer</function> are equally good)
|
||||
</para>
|
||||
<para>
|
||||
This list is consistent with PHP 4.0.6. For an alias list that
|
||||
updates daily, have a look <ulink url="&url.zend.aliaslist;">here</ulink>.
|
||||
This list is consistent with PHP 4.0.6.
|
||||
</para>
|
||||
<para>
|
||||
<table>
|
||||
|
|
|
@ -1,94 +1,95 @@
|
|||
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||
<!-- $Revision: 1.20 $ -->
|
||||
<!-- $Revision: 1.21 $ -->
|
||||
<appendix id="migration">
|
||||
<title>Mirgrando do PHP/FI para o PHP 3</title>
|
||||
<title>Migrating from PHP/FI 2 to PHP 3</title>
|
||||
|
||||
<section id="migration.about">
|
||||
<title>Sobre as incompatibilidades do 3.0</title>
|
||||
<title>About the incompatibilities in 3.0</title>
|
||||
|
||||
<simpara>
|
||||
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.
|
||||
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.
|
||||
</simpara>
|
||||
|
||||
<simpara>
|
||||
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.
|
||||
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.
|
||||
</simpara>
|
||||
|
||||
<simpara>
|
||||
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.
|
||||
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.
|
||||
</simpara>
|
||||
|
||||
<simpara>
|
||||
Um programa que converte automaticamente seus scripts em PHP/FI 2.0 existe.
|
||||
Ele pode ser encontrado no subdiretório <filename class="directory">convertor</filename>
|
||||
da distribuição do PHP 3.0. Este programa apenas capta alterações de sintaxe,
|
||||
portanto você deve ler atentamente este capítulo.
|
||||
A conversion program that can automatically convert your old
|
||||
PHP/FI 2.0 scripts exists. It can be found in the
|
||||
<filename class="directory">convertor</filename> subdirectory of the PHP 3.0
|
||||
distribution. This program only catches the syntax changes though,
|
||||
so you should read this chapter carefully anyway.
|
||||
</simpara>
|
||||
</section>
|
||||
|
||||
<section id="migration.startendtags">
|
||||
<title>Tags de Começo/fim</title>
|
||||
<title>Start/end tags</title>
|
||||
|
||||
<para>
|
||||
A primeira coisa que você provavelmente irá reparar é que as tags de
|
||||
começo e fim do PHP mudaram. O velho foi <literal><? ></literal>
|
||||
modificado para três formas possíveis:
|
||||
The first thing you probably will notice is that PHP's start and end
|
||||
tags have changed. The old <literal><? ></literal> form has been
|
||||
replaced by three new possible forms:
|
||||
<example>
|
||||
<title>Migrando: da velha tag começo/fim</title>
|
||||
<title>Migration: old start/end tags</title>
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
<? echo "Este é um código em PHP/FI 2.0.\n"; >
|
||||
<? echo "This is PHP/FI 2.0 code.\n"; ?>
|
||||
]]>
|
||||
</programlisting>
|
||||
</example>
|
||||
Como na versão 2.0, PHP/FI também suporta esta variação:
|
||||
As of version 2.0, PHP/FI also supports this variation:
|
||||
<example>
|
||||
<title>Migrando: primeira forma das tags começo/fim</title>
|
||||
<title>Migration: first new start/end tags</title>
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
<? echo "Este é um código em PHP 3.0!\n"; ?>
|
||||
<? echo "This is PHP 3.0 code!\n"; ?>
|
||||
]]>
|
||||
</programlisting>
|
||||
</example>
|
||||
|
||||
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:
|
||||
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:
|
||||
|
||||
<example>
|
||||
<title>Migrando: segunda forma das tags começo/fim</title>
|
||||
<title>Migration: second new start/end tags</title>
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
<?php echo "Este é um código em PHP 3.0!\n"; ?>
|
||||
<?php echo "This is PHP 3.0 code!\n"; ?>
|
||||
]]>
|
||||
</programlisting>
|
||||
</example>
|
||||
|
||||
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:
|
||||
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:
|
||||
|
||||
<example>
|
||||
<title>Migrando: terceira forma das tags começo/fim</title>
|
||||
<title>Migration: third new start/end tags</title>
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
<script language="php">
|
||||
|
||||
echo "Este é um código em PHP 3.0!\n";
|
||||
echo "This is PHP 3.0 code!\n";
|
||||
|
||||
</script>
|
||||
]]>
|
||||
|
@ -98,66 +99,67 @@
|
|||
</section>
|
||||
|
||||
<section id="migration.if-endif">
|
||||
<title>sintaxe if..endif</title>
|
||||
<title>if..endif syntax</title>
|
||||
|
||||
<para>
|
||||
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:
|
||||
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:
|
||||
<example>
|
||||
<title>Migrando: velha sintaxe if..endif</title>
|
||||
<title>Migration: old if..endif syntax</title>
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
if ($foo);
|
||||
echo "sim\n";
|
||||
echo "yep\n";
|
||||
elseif ($bar);
|
||||
echo "quase\n";
|
||||
echo "almost\n";
|
||||
else;
|
||||
echo "não\n";
|
||||
echo "nope\n";
|
||||
endif;
|
||||
]]>
|
||||
</programlisting>
|
||||
</example>
|
||||
<example>
|
||||
<title>Migrando: nova sintaxe if..endif</title>
|
||||
<title>Migration: new if..endif syntax</title>
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
if ($foo):
|
||||
echo "sim\n";
|
||||
echo "yep\n";
|
||||
elseif ($bar):
|
||||
echo "quase\n";
|
||||
echo "almost\n";
|
||||
else:
|
||||
echo "não\n";
|
||||
echo "nope\n";
|
||||
endif;
|
||||
]]>
|
||||
</programlisting>
|
||||
</example>
|
||||
|
||||
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).
|
||||
Notice that the semicolons have been replaced by colons in all
|
||||
statements but the one terminating the expression (endif).
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="migration-while">
|
||||
<title>sintaxe while</title>
|
||||
<title>while syntax</title>
|
||||
<para>
|
||||
Assim como o if...endif, a sintaxe do while...endwhile foi alterada:
|
||||
Just like with if..endif, the syntax of while..endwhile has changed
|
||||
as well:
|
||||
<example>
|
||||
<title>Migrando: a velha sintaxe do while..endwhile</title>
|
||||
<title>Migration: old while..endwhile syntax</title>
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
while ($mais_a_vir);
|
||||
while ($more_to_come);
|
||||
...
|
||||
endwhile;
|
||||
]]>
|
||||
</programlisting>
|
||||
</example>
|
||||
<example>
|
||||
<title>Migrando: nova sintaxe do while..endwhile</title>
|
||||
<title>Migration: new while..endwhile syntax</title>
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
while ($mais_a_vir):
|
||||
while ($more_to_come):
|
||||
...
|
||||
endwhile;
|
||||
]]>
|
||||
|
@ -166,22 +168,22 @@ endwhile;
|
|||
</para>
|
||||
<warning>
|
||||
<simpara>
|
||||
Se você usar a velha sintaxe do while...endwhile no PHP 3.0,
|
||||
você irá obter um loop que nunca-termina.
|
||||
If you use the old while..endwhile syntax in PHP 3.0,
|
||||
you will get a never-ending loop.
|
||||
</simpara>
|
||||
</warning>
|
||||
</section>
|
||||
|
||||
<section id="migration.expr">
|
||||
<title>Tipos de Expressões</title>
|
||||
<title>Expression types</title>
|
||||
<simpara>
|
||||
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.
|
||||
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.
|
||||
</simpara>
|
||||
<para>
|
||||
Considere este exemplo:
|
||||
Consider this example:
|
||||
<informalexample>
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
|
@ -197,17 +199,20 @@ while ("" != $key) {
|
|||
</programlisting>
|
||||
</informalexample>
|
||||
|
||||
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 <literal>""</literal> não é igual à <literal>"0"</literal>, 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 <literal>atoi("")</literal> é <literal>0</literal>, e <literal>variablelist</literal>
|
||||
também é <literal>0</literal>, deste que <literal>0==0</literal>, o loop não executa mais de uma vez.
|
||||
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 <literal>""</literal> does not equal
|
||||
<literal>"0"</literal>, 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 <literal>atoi("")</literal> which is
|
||||
<literal>0</literal>, and <literal>variablelist</literal> which is
|
||||
also <literal>0</literal>, and since <literal>0==0</literal>, the
|
||||
loop doesn't go through even once.
|
||||
</para>
|
||||
<para>
|
||||
A correção para iso é simples. Troque aquele while por:
|
||||
The fix for this is simple. Replace the while statement with:
|
||||
<informalexample>
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
|
@ -219,57 +224,60 @@ while ((string)$key != "") {
|
|||
</section>
|
||||
|
||||
<section id="migration.errors">
|
||||
<title>Mensagens de erro foram alteradas</title>
|
||||
<title>Error messages have changed</title>
|
||||
<simpara>
|
||||
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.
|
||||
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.
|
||||
</simpara>
|
||||
</section>
|
||||
|
||||
<section id="migration.booleval">
|
||||
<title>Short-circuited boolean evaluation</title>
|
||||
<simpara>
|
||||
No PHP 3.0 a avaliação booleana é short-circuited. Isto significa que
|
||||
uma expressão como esta <literal>(1 || teste_me())</literal>, da função
|
||||
<function>teste_me</function> não seria executada porque nada pode mudar
|
||||
o resultado da expressão após <literal>1</literal>.
|
||||
In PHP 3.0 boolean evaluation is short-circuited. This means that
|
||||
in an expression like <literal>(1 || test_me())</literal>, the
|
||||
function <function>test_me</function> would not be executed since
|
||||
nothing can change the result of the expression after the
|
||||
<literal>1</literal>.
|
||||
</simpara>
|
||||
|
||||
<simpara>
|
||||
Esta é uma pequena incompatibilidade, mas poderá causar side-effects
|
||||
inesperados.
|
||||
This is a minor compatibility issue, but may cause unexpected
|
||||
side-effects.
|
||||
</simpara>
|
||||
</section>
|
||||
|
||||
<section id="migration.truefalse">
|
||||
<title>Funções &true;/&false; retornam valores</title>
|
||||
<title>Function &true;/&false; return values</title>
|
||||
<simpara>
|
||||
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 <literal>$fp = fopen("/seu/arquivo") or fail("merda!");</literal>.
|
||||
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.
|
||||
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 <literal>$fp = fopen("/your/file") or
|
||||
fail("darn!");</literal>. 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.
|
||||
</simpara>
|
||||
<para>
|
||||
<example>
|
||||
<title>Migrando do 2.0: retornando valores, código antigo</title>
|
||||
<title>Migration from 2.0: return values, old code</title>
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
$fp = fopen($arquivo, "r");
|
||||
$fp = fopen($file, "r");
|
||||
if ($fp == -1);
|
||||
echo("Não foi possível abrir $arquivo para leitura<br>\n");
|
||||
echo("Could not open $file for reading<br>\n");
|
||||
endif;
|
||||
]]>
|
||||
</programlisting>
|
||||
</example>
|
||||
<example>
|
||||
<title>Migrando do 2.0: retornando valores, novo código</title>
|
||||
<title>Migration from 2.0: return values, new code</title>
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
$fp = @fopen($arquivo, "r") or print("Não foi possível abrir $arquivo para leitura<br>\n");
|
||||
$fp = @fopen($file, "r") or print("Could not open $file for reading<br>\n");
|
||||
]]>
|
||||
</programlisting>
|
||||
</example>
|
||||
|
@ -277,60 +285,65 @@ $fp = @fopen($arquivo, "r") or print("Não foi possível abrir $arqu
|
|||
</section>
|
||||
|
||||
<section id="migration-other">
|
||||
<title>Outras incompatibilidades</title>
|
||||
<title>Other incompatibilities</title>
|
||||
|
||||
<itemizedlist>
|
||||
<listitem><simpara>
|
||||
O módulo do PHP 3.0 para o Apache não suporta versões anteriores à 1.2.
|
||||
Apache 1.2 ou atual é requerido.
|
||||
The PHP 3.0 Apache module no longer supports Apache versions
|
||||
prior to 1.2. Apache 1.2 or later is required.
|
||||
</simpara></listitem>
|
||||
|
||||
<listitem><simpara>
|
||||
<function>echo</function> não suporta mais strings formatadas.
|
||||
Use a função <function>printf</function> para isto.
|
||||
<function>echo</function> no longer supports a format string.
|
||||
Use the <function>printf</function> function instead.
|
||||
</simpara></listitem>
|
||||
|
||||
<listitem><simpara>
|
||||
No PHP/FI 2.0, uma execução "side-effect" faz com que <literal>$foo[0]</literal>
|
||||
tenha o mesmo efeito que <literal>$foo</literal>. No PHP 3.0 isto não é verdadeiro.
|
||||
In PHP/FI 2.0, an implementation side-effect caused
|
||||
<literal>$foo[0]</literal> to have the same effect as
|
||||
<literal>$foo</literal>. This is not true for PHP 3.0.
|
||||
</simpara></listitem>
|
||||
|
||||
<listitem>
|
||||
<simpara>
|
||||
Ler arrays com <literal>$array[]</literal> não é mais
|
||||
suportado
|
||||
Reading arrays with <literal>$array[]</literal> is no longer
|
||||
supported
|
||||
</simpara>
|
||||
<simpara>
|
||||
Isto é, você não pode atravessar um array fazendo um loop que contém <literal>$data = $array[]</literal>.
|
||||
Ao invés disso use <function>current</function> e <function>next</function>.
|
||||
That is, you cannot traverse an array by having a loop that does
|
||||
<literal>$data = $array[]</literal>. Use <function>current</function>
|
||||
and <function>next</function> instead.
|
||||
</simpara>
|
||||
<simpara>
|
||||
Também, <literal>$array1[] = $array2</literal> não adiciona
|
||||
valores de <literal>$array2</literal> à <literal>$array1</literal>,
|
||||
mas adiciona <literal>$array2</literal> como a última entrada de
|
||||
<literal>$array1</literal>. Veja também o suporte ao array multidimensional.
|
||||
Also, <literal>$array1[] = $array2</literal> does not
|
||||
append the values of <literal>$array2</literal> to
|
||||
<literal>$array1</literal>, but appends
|
||||
<literal>$array2</literal> as the last entry of
|
||||
<literal>$array1</literal>. See also multidimensional array
|
||||
support.
|
||||
</simpara>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<simpara>
|
||||
<literal>"+"</literal> 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 <literal>"."</literal> para concatenar.
|
||||
<literal>"+"</literal> is no longer overloaded as a
|
||||
concatenation operator for strings, instead it converts it's
|
||||
arguments to numbers and performs numeric addition. Use
|
||||
<literal>"."</literal> instead.
|
||||
</simpara>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
|
||||
<example>
|
||||
<title>Migrando do 2.0: concatenação de strings</title>
|
||||
<title>Migration from 2.0: concatenation for strings</title>
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
echo "1" + "1";
|
||||
]]>
|
||||
</programlisting>
|
||||
<para>
|
||||
No PHP 2.0 isto retornaria echo 11, no PHP 3.0 isto
|
||||
retornará echo 2. Ao invés disso use:
|
||||
In PHP 2.0 this would echo 11, in PHP 3.0 it would
|
||||
echo 2. Instead use:
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
echo "1"."1";
|
||||
|
@ -345,7 +358,7 @@ echo $a + $b;
|
|||
</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Isto irá retornar echo 2 em ambas versões do PHP 2.0 e 3.0.
|
||||
This would echo 2 in both PHP 2.0 and 3.0.
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
$a = 1;
|
||||
|
@ -353,7 +366,7 @@ $b = 1;
|
|||
echo $a.$b;
|
||||
]]>
|
||||
</programlisting>
|
||||
Isto retornará echo 11 no PHP 3.0.
|
||||
This will echo 11 in PHP 3.0.
|
||||
</para>
|
||||
</example>
|
||||
</section>
|
||||
|
|
|
@ -1,43 +1,43 @@
|
|||
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||
<!-- $Revision: 1.26 $ -->
|
||||
<!-- $Revision: 1.27 $ -->
|
||||
<appendix id="migration4">
|
||||
<title>Migrando do PHP 3 para o PHP 4</title>
|
||||
<title>Migrating from PHP 3 to PHP 4</title>
|
||||
|
||||
<section id='migration4.changes'>
|
||||
<title>O que mudou no PHP 4</title>
|
||||
<title>What has changed in PHP 4</title>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="migration4.php4.with.php3">
|
||||
<title>Rodando PHP 3 e PHP 4 simultaneamente</title>
|
||||
<title>Running PHP 3 and PHP 4 concurrently</title>
|
||||
<simpara>
|
||||
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.
|
||||
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.
|
||||
</simpara>
|
||||
<simpara>
|
||||
Esta opção é suportada nas seguintes plataformas:
|
||||
This feature is known to work on the following platforms:
|
||||
</simpara>
|
||||
<itemizedlist>
|
||||
<listitem><simpara>Linux com os recentes binutils (binutils 2.9.1.0.25 testado) </simpara></listitem>
|
||||
<listitem><simpara>Solaris 2.5 ou superior</simpara></listitem>
|
||||
<listitem><simpara>FreeBSD (3.2, 4.0 testado)</simpara></listitem>
|
||||
<listitem><simpara>Linux with recent binutils (binutils 2.9.1.0.25 tested) </simpara></listitem>
|
||||
<listitem><simpara>Solaris 2.5 or better</simpara></listitem>
|
||||
<listitem><simpara>FreeBSD (3.2, 4.0 tested)</simpara></listitem>
|
||||
</itemizedlist>
|
||||
<para>
|
||||
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:
|
||||
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:
|
||||
<informalexample>
|
||||
<programlisting role="configure">
|
||||
<![CDATA[
|
||||
|
@ -53,15 +53,15 @@ $ ./configure \
|
|||
</section>
|
||||
|
||||
<section id="migration4.configuration">
|
||||
<title>Migrando os arquivos de configuração</title>
|
||||
<title>Migrating Configuration Files</title>
|
||||
<para>
|
||||
O arquivo de configuração global, <filename>php3.ini</filename>,
|
||||
foi alterado para ete nome &php.ini;.
|
||||
The global configuration file, <filename>php3.ini</filename>,
|
||||
has changed its name to &php.ini;.
|
||||
</para>
|
||||
<para>
|
||||
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.
|
||||
For the Apache configuration file, there are slightly more
|
||||
changes. The MIME types recognized by the PHP module have
|
||||
changed.
|
||||
<informalexample>
|
||||
<programlisting role="apache">
|
||||
<![CDATA[
|
||||
|
@ -72,9 +72,9 @@ application/x-httpd-php3-source --> application/x-httpd-php-source
|
|||
</informalexample>
|
||||
</para>
|
||||
<para>
|
||||
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:
|
||||
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:
|
||||
<informalexample>
|
||||
<programlisting>
|
||||
<![CDATA[
|
||||
|
@ -88,11 +88,11 @@ AddType application/x-httpd-php-source .phps
|
|||
</informalexample>
|
||||
</para>
|
||||
<simpara>
|
||||
Além disso, os nomes das diretiva do PHP para o Apache foram alteradas.
|
||||
In addition, the PHP directive names for Apache have changed.
|
||||
</simpara>
|
||||
<para>
|
||||
Começando com o PHP 4.0, há quatro diretivas para o Apache relacionadas
|
||||
ao PHP:
|
||||
Starting with PHP 4.0, there are only four Apache directives
|
||||
that relate to PHP:
|
||||
<informalexample>
|
||||
<programlisting role="apache">
|
||||
<![CDATA[
|
||||
|
@ -105,23 +105,17 @@ php_admin_flag [PHP directive name] [On|Off]
|
|||
</informalexample>
|
||||
</para>
|
||||
<simpara>
|
||||
Há duas diferenças entre os valores do Admin e do não admin:
|
||||
There are two differences between the Admin values and the non admin values:
|
||||
</simpara>
|
||||
<itemizedlist>
|
||||
<listitem><simpara>Os valores Admin (ou os flags) só aparecem no server-wide dos arquivos de configuração
|
||||
do apache (e.g., httpd.conf).</simpara></listitem>
|
||||
<listitem><simpara>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.</simpara></listitem>.
|
||||
<listitem><simpara>Admin values (or flags) can only appear in the server-wide apache configuration files (e.g., httpd.conf).</simpara></listitem>
|
||||
<listitem><simpara>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.</simpara></listitem>
|
||||
</itemizedlist>
|
||||
<simpara>
|
||||
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 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.
|
||||
</simpara>
|
||||
<para>
|
||||
Para converter seus arquivos de configuração do Apache, rode o script apconf-conv.sh (distponível no
|
||||
diretório /scripts/apache). Exemplo:
|
||||
To convert your Apache configuration files, run the apconf-conv.sh script (available in the scripts/apache/ directory). For example:
|
||||
<informalexample>
|
||||
<programlisting role="shell">
|
||||
<![CDATA[
|
||||
|
@ -131,11 +125,10 @@ php_admin_flag [PHP directive name] [On|Off]
|
|||
</informalexample>
|
||||
</para>
|
||||
<simpara>
|
||||
Seu arquivo de configuração original será salve como httpd.conf.orig.
|
||||
Your original configuration file will be saved in httpd.conf.orig.
|
||||
</simpara>
|
||||
<para>
|
||||
Para converter seus arquivos .htaccess, rode o script aphtaccess-conv.sh (disponível no
|
||||
diretório scripts/apache), exemplo:
|
||||
To convert your .htaccess files, run the aphtaccess-conv.sh script (available in the scripts/apache/ directory as well):
|
||||
<informalexample>
|
||||
<programlisting role="shell">
|
||||
<![CDATA[
|
||||
|
@ -145,316 +138,315 @@ php_admin_flag [PHP directive name] [On|Off]
|
|||
</informalexample>
|
||||
</para>
|
||||
<simpara>
|
||||
Como já foi dito, seus antigos arquivos .htacces serão salvos com o prefixo .orig.
|
||||
Likewise, your old .htaccess files will be saved with an .orig prefix.
|
||||
</simpara>
|
||||
<simpara>
|
||||
A conversão dos scripts requer que o awk esteja instalado.
|
||||
The conversion scripts require awk to be installed.
|
||||
</simpara>
|
||||
</section>
|
||||
|
||||
<section id='migration4.parser'>
|
||||
<title>Comportamento da Análise</title>
|
||||
<title>Parser behavior</title>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
<para>
|
||||
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 <literal>for</literal> ou <literal>while</literal>,
|
||||
um bloco de instruções <literal>if</literal> ou <literal>switch</literal> começando
|
||||
em um arquivo e terminar o loop, <literal>else</literal>, <literal>endif</literal>,
|
||||
<literal>case</literal> ou <literal>break</literal> em um arquivo diferente.
|
||||
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 <literal>for</literal> or <literal>while</literal> loop,
|
||||
an <literal>if</literal> statement or a <literal>switch</literal>
|
||||
block in one file and have the end of loop,
|
||||
<literal>else</literal>, <literal>endif</literal>,
|
||||
<literal>case</literal> or <literal>break</literal> statements in
|
||||
a different file.
|
||||
</para>
|
||||
<para>
|
||||
Ainda é permitido incluir códigos adicionaisdentro dos laços ou
|
||||
estruturas de controle, somente os controles chaves e os correspondentes
|
||||
<literal>(....)</literal> tem que estar compilados na mesma unidade
|
||||
(arquivo ou <function>eval</function>ed string).
|
||||
It still perfectly legal to include additional code within loops
|
||||
or other control structures, only the controlling keywords and
|
||||
corresponding curly braces <literal>{...}</literal> have to be
|
||||
within the same compile unit (file or <function>eval</function>ed
|
||||
string).
|
||||
</para>
|
||||
<para>
|
||||
Isto não deve prejudicar muito considerando que um código como este
|
||||
é considerado mal feito de qualquer maneira.
|
||||
This should not harm to much as spreading code like this should be
|
||||
considered as very bad style anyway.
|
||||
</para>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id='migration4.error-reporting'>
|
||||
<title>Relatório de erros</title>
|
||||
<title>Error reporting</title>
|
||||
|
||||
<section id='migration4.error-reporting.config'>
|
||||
<title>Mudanças na Configuração</title>
|
||||
<title>Configuration changes</title>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
<para>
|
||||
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 <literal>E_ALL</literal>.
|
||||
Parece complicado? Bem, vamos dizer que você quer todas as advertências
|
||||
categorizadas na constante simbólica <literal>E_NOTICE</literal>. Então você
|
||||
deverá colocar o seguinte em seu &php.ini;: <literal>error_reporting =
|
||||
E_ALL & - ( E_NOTICE )</literal>. Se você quiser suprir as
|
||||
advertências você deve adicionar a constante apropriada dentro do
|
||||
parêntese usando o operador '|':
|
||||
<literal>erro_reporting = E_ALL & ~ ( E_NOTICE | E_WARNING )</literal>.
|
||||
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
|
||||
<literal>E_ALL</literal>. 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
|
||||
<literal>E_NOTICE</literal>. Then you'll put the following into
|
||||
your &php.ini;: <literal>error_reporting =
|
||||
E_ALL & ~ ( E_NOTICE )</literal>. If you want to suppress
|
||||
warnings too you add up the appropriate constant within the
|
||||
braces using the binary or operator '|':
|
||||
<literal>error_reporting= E_ALL & ~ ( E_NOTICE | E_WARNING
|
||||
)</literal>.
|
||||
</para>
|
||||
<warning>
|
||||
<para>
|
||||
Ao atualizar códigos ou servidores do PHP 3 para PHP 4 você
|
||||
deve checar as configurações e chamadas ao <function>error_reporting</function>
|
||||
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.
|
||||
When upgrading code or servers from PHP 3 to PHP 4 you should
|
||||
check these settings and calls to
|
||||
<function>error_reporting</function> 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.
|
||||
</para>
|
||||
</warning>
|
||||
<warning>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
</warning>
|
||||
</section>
|
||||
|
||||
<section id='migration4.error-reporting.additions'>
|
||||
<title>Mensagens de advertência adicionais</title>
|
||||
<title>Additional warning messages</title>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
<para>
|
||||
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
|
||||
<literal>$_SERVER[REQUEST_METHOD]</literal>. Altere isto para
|
||||
<literal>$_SERVER['REQUEST_METHOD']</literal> que fará
|
||||
com que o parser fique feliz e melhorará extremamente o
|
||||
estilo e segurança do seu 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
|
||||
<literal>$_SERVER[REQUEST_METHOD]</literal>. Changing it
|
||||
to <literal>$_SERVER['REQUEST_METHOD']</literal> will
|
||||
make the parser happy and greatly improve the style and security
|
||||
of your code.
|
||||
</para>
|
||||
<para>
|
||||
Outra coisa que o PHP 4 agora lhe informa é sobre o uso
|
||||
de variáveis ou elementos de array não inicializados.
|
||||
Another thing PHP 4 will now tell you about is the use of
|
||||
uninitialized variables or array elements.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
|
||||
<section id='migration4.initializers'>
|
||||
<title>Inicializadores</title>
|
||||
<title>Initializers</title>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
<para>
|
||||
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.
|
||||
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>
|
||||
</section>
|
||||
|
||||
<section id='migration4.empty'>
|
||||
<title><literal>empty("0")</literal></title>
|
||||
<para>
|
||||
Talvez a mudança mais controversa no comportamento aconteceu na função
|
||||
<function>empty</function>. Uma string que contém somente caracteres
|
||||
' 0 ' (zero) agora é considerada vazia enquanto no PHP 3 ela não era.
|
||||
The perhaps most controversial change in behavior has happened to the
|
||||
behavior of the <function>empty</function>. A String containing
|
||||
only the character '0' (zero) is now considered empty while it
|
||||
wasn't in PHP 3.
|
||||
</para>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id='migration4.missing'>
|
||||
<title>Funções abandonadas</title>
|
||||
<title>Missing functions</title>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
|
||||
<section id='migration4.missing.concept'>
|
||||
<title>Funções abandonadas devido à mudanças conceptuais</title>
|
||||
<title>Functions missing due to conceptual changes</title>
|
||||
<para>
|
||||
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
|
||||
<function>short_tags</function> não existe mais. Você ainda
|
||||
pode mudar o comportamento dos parsers setando o valor
|
||||
propriedade no arquivo &php.ini.
|
||||
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 <function>short_tags</function> no longer
|
||||
exists. You can still change the parsers behavior by setting
|
||||
appropriate values in the &php.ini; file.
|
||||
</para>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id='migration4.deprecate'>
|
||||
<title>Depcritamento de funções e extensões</title>
|
||||
<title>Deprecate functions and extensions</title>
|
||||
<para>
|
||||
As extensões dos banco de dados Adabas e Solid não existem mais.
|
||||
Ao inés delas foi unificado o ODBC.
|
||||
The Adabas and Solid database extensions are no more. Long live
|
||||
the unified ODBC extension instead.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id='migration4.unset'>
|
||||
<title>Mudança de status para <function>unset</function></title>
|
||||
<title>Changed status for <function>unset</function></title>
|
||||
<para>
|
||||
<function>unset</function>, embora ainda disponível, é
|
||||
implementado como um construtor de linguagem melhor que uma função.
|
||||
<function>unset</function>, although still available, is
|
||||
implemented as a language construct rather than a function.
|
||||
</para>
|
||||
<para>
|
||||
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
|
||||
<function>unset</function>, mas testar "unset" usando
|
||||
<function>function_exists</function> retornará &false;
|
||||
porque com outros construtores de linguagens que observam
|
||||
funcções tais como o <function>echo</function>.
|
||||
This does not have any consequences on the behavior of
|
||||
<function>unset</function>, but testing for "unset" using
|
||||
<function>function_exists</function> will return &false; as it would with
|
||||
other language constructs that look like functions such as
|
||||
<function>echo</function>.
|
||||
</para>
|
||||
<para>
|
||||
Uma otura mudança mais prática é que não é mais possível chamar
|
||||
<function>unset</function> indiretamente, isso é, <literal>$func="unset"; $func($algumavar)</literal>
|
||||
não irá mais funcionar.
|
||||
Another more practical change is that it is no longer possible to
|
||||
call <function>unset</function> indirectly, that is
|
||||
<literal>$func="unset"; $func($somevar)</literal> won't work
|
||||
anymore.
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section id='migration4.extensions'>
|
||||
<title>Extensões PHP 3</title>
|
||||
<title>PHP 3 extension</title>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id='migration4.strings'>
|
||||
<title>Substituição de variáveis nas strings</title>
|
||||
<title>Variable substitution in strings</title>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
<para>
|
||||
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 do so you have to enclose your variables with curly braces with
|
||||
the dollar sign immediately following the opening brace:
|
||||
<literal>{$...}</literal>
|
||||
</para>
|
||||
<para>
|
||||
Para embutir o valor de um objeto membro de uma variável
|
||||
dentro de uma string simplesmente escreva <literal>"texto {$obj->membro} texto"</literal>
|
||||
enquanto no PHP 3 você tinha que usar uma coisa como esta
|
||||
<literal>"texto ".$obj->membro." texto"</literal>.
|
||||
To embed the value of an object member variable into a string you
|
||||
simply write <literal>"text {$obj->member} text"</literal> while
|
||||
in PHP 3 you had to use something like <literal>"text
|
||||
".$obj->member." text"</literal>.
|
||||
</para>
|
||||
<para>
|
||||
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 <literal>{$</literal>
|
||||
no seu código e substituindo eles por
|
||||
<literal>\{$</literal> usando sua ferramenta de
|
||||
procura-e-substituição favorita.
|
||||
</para>
|
||||
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
|
||||
<literal>{$</literal> in your code and by replacing it with
|
||||
<literal>\{$</literal> with your favorite search-and-replace
|
||||
tool.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id='migration4.cookies'>
|
||||
<title>Cookies</title>
|
||||
<para>
|
||||
O PHP 3 tinha um mau hábito de configurar os cookies na ordem
|
||||
reversa das chamadas <function>setcookie</function> 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.
|
||||
PHP 3 had the bad habit of setting cookies in the reverse order
|
||||
of the <function>setcookie</function> 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.
|
||||
</para>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id='migration4.variables'>
|
||||
<title>Manipulação de variáveis globais</title>
|
||||
<title>Handling of global variables</title>
|
||||
<para>
|
||||
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 <link linkend="references.global">.
|
||||
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 <link linkend="references.global">
|
||||
<literal>global</literal> references section</link>.
|
||||
</para>
|
||||
<example>
|
||||
<title>Migração das variáveis globais</title>
|
||||
<title>Migration of global variables</title>
|
||||
<programlisting role="php">
|
||||
<![CDATA[
|
||||
<?php
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -1,15 +1,15 @@
|
|||
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||
<!-- $Revision: 1.3 $ -->
|
||||
<!-- $Revision: 1.4 $ -->
|
||||
<refentry id="reserved.constants.core">
|
||||
<refnamediv>
|
||||
<refname>Constantes Pré-definidas do Núcleo</refname>
|
||||
<refpurpose>Constantes definidas no núcleo do PHP, Zend, e módulos SAPI</refpurpose>
|
||||
<refname>Core Predefined Constants</refname>
|
||||
<refpurpose>Constants defined in the PHP core, Zend, and SAPI modules</refpurpose>
|
||||
</refnamediv>
|
||||
<refsect1>
|
||||
<title>Descrição</title>
|
||||
<title>Description</title>
|
||||
<simpara>
|
||||
Estas constantes são definidas pelo núcleo do PHP. Isto
|
||||
inclui o PHP, a Zend engine, e os módulos SAPI.
|
||||
These constants are defined by the PHP core. This includes PHP,
|
||||
the Zend engine, and SAPI modules.
|
||||
</simpara>
|
||||
<variablelist>
|
||||
<varlistentry>
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||
<!-- $Revision: 1.5 $ -->
|
||||
<!-- $Revision: 1.6 $ -->
|
||||
|
||||
<!-- DOCNOTE: some constants listed here are also there at
|
||||
reference/info/constants.xml. Further decision is needed
|
||||
|
@ -8,13 +8,13 @@
|
|||
deleted from here to have a consistent standard constants list. -->
|
||||
<refentry id="reserved.constants.standard">
|
||||
<refnamediv>
|
||||
<refname>Constantes Padrões Pré-definidas</refname>
|
||||
<refpurpose>Constantes definidas no PHP por padrão</refpurpose>
|
||||
<refname>Standard Predefined Constants</refname>
|
||||
<refpurpose>Constants defined in PHP by default</refpurpose>
|
||||
</refnamediv>
|
||||
<refsect1>
|
||||
<title>Descrição</title>
|
||||
<title>Description</title>
|
||||
<simpara>
|
||||
Estas constantes são definidas por padrão no PHP.
|
||||
These constants are defined in PHP by default.
|
||||
</simpara>
|
||||
<variablelist>
|
||||
<varlistentry>
|
||||
|
|
|
@ -1,23 +1,23 @@
|
|||
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||
<!-- $Revision: 1.28 $ -->
|
||||
<!-- $Revision: 1.29 $ -->
|
||||
<appendix id="resource">
|
||||
<title>Lsita de Tipos de Recursos</title>
|
||||
<title>List of Resource Types</title>
|
||||
<para>
|
||||
A seguir há uma lista de funções que criam, usam e destróem
|
||||
recursos do PHP. A função <function>is_resource</function> podem
|
||||
ser usadas para determinar se a variável é um recurso e
|
||||
o <function>get_resource_type</function> irá retornar o tipo
|
||||
de recurso que está sendo usado.
|
||||
The following is a list of functions which create, use or destroy
|
||||
PHP resources. The function <function>is_resource</function> can be
|
||||
used to determine if a variable is a resource and
|
||||
<function>get_resource_type</function> will return the type of
|
||||
resource it is.
|
||||
<table>
|
||||
<title>Tipos de Recursos</title>
|
||||
<title>Resource Types</title>
|
||||
<tgroup cols="5">
|
||||
<thead>
|
||||
<row>
|
||||
<entry>Nome do Tipo de Recurso</entry>
|
||||
<entry>Criado por</entry>
|
||||
<entry>Usado por</entry>
|
||||
<entry>Destroído por</entry>
|
||||
<entry>Definição</entry>
|
||||
<entry>Resource Type Name</entry>
|
||||
<entry>Created By</entry>
|
||||
<entry>Used By</entry>
|
||||
<entry>Destroyed By</entry>
|
||||
<entry>Definition</entry>
|
||||
</row>
|
||||
</thead>
|
||||
<tbody>
|
||||
|
|
|
@ -1,18 +1,17 @@
|
|||
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||
<!-- $Revision: 1.8 $ -->
|
||||
<!-- $Revision: 1.9 $ -->
|
||||
|
||||
<appendix id="tokens">
|
||||
<title>Lista dos Símbolos od Parse</title>
|
||||
<title>List of Parser Tokens</title>
|
||||
<para>
|
||||
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 <literal>"Parse error: unexpected T_SR, expecting ',' or ';' in
|
||||
script.php on line 10."</literal>
|
||||
Various parts of the PHP language are represented internally by types like
|
||||
T_SR. PHP outputs identifiers like this one in parse errors, like
|
||||
<literal>"Parse error: unexpected T_SR, expecting ',' or ';' in script.php on line 10."</literal>
|
||||
</para>
|
||||
<para>
|
||||
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.
|
||||
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.
|
||||
</para>
|
||||
<table>
|
||||
<title>Tokens</title>
|
||||
|
|
Loading…
Reference in a new issue