PHP Velho Oeste 2024

Alterações Incompatíveis com Versões Anteriores

A maioria dos códigos PHP 4 existentes deve funcionar sem mudanças, mas você deve ter atenção às seguintes alterações incompatíves com versões anteriores:

  • Existem algumas palavras reservadas novas.
  • strrpos() e strripos() agora usam o texto todo como busca (needle).
  • O uso ilegal de posição de string causará E_ERROR ao invés de E_WARNING. Um exemplo de uso ilegal é: $str = 'abc'; unset($str[0]);.
  • array_merge() foi alterada para aceitar somente arrays. Se uma variavel diferente de array for passada, um E_WARNING será lançado para cada parâmetro. Tenha cuidado porque seu código pode iniciar emitindo um E_WARNING.
  • A variável de servidor PATH_TRANSLATED não é mais setada implicitamente no Apache2 SAPI em contraste com o ocorrido no PHP 4, onde ele é setado com o mesmo valor que a variável de servidor SCRIPT_FILENAME quando não era populada pelo Apache. Esta mudança foi realizada para seguir a » Especificação CGI/1.1. Por favor consulte o » bug #23610 para mais informações, e veja mais sobre a descrição do $_SERVER['PATH_TRANSLATED'] no manual. Este problema afeta as versões >= 4.3.2 do PHP.
  • A constante T_ML_COMMENT não é mais definida pela extensão Tokenizer. Se o error_reporting estiver configurado para E_ALL, o PHP irá gerar um aviso. Embora o T_ML_COMMENT não ser usado totalmente, ele é definido no PHP 4. Em ambas versões, PHP 4 e PHP 5, // e /* */ são consideradas como constantes T_COMMENT . Entrentanto, o estilo de comentários do PHPDoc /** */, que começou a ser interpretado pelo PHP 5, é reconhecido como T_DOC_COMMENT.
  • $_SERVER deve ser populado com argc e argv se variables_order inclue "S". Se você configurou especificamente seu sistema para não criar a variável $_SERVER, então é claro que não estará lá. Esta alteração faz com que argc e argv sempre esteja disponível na versão CLI independente da configuração da variables_order. Assim como, a versão CLI agora sempre popula as variáveis globais $argc e $argv.
  • Um objeto sem propriedades não será mais considerado "vazio".
  • Em alguns casos as classes devem ser declaradas antes de serem usadas. Isto acontece somente se algumas das novas funcionalidades do PHP 5 (como as interfaces) são usadas. Caso contrário, o comportamento é o antigo.
  • get_class(), get_parent_class() e get_class_methods() agora retornam o nome das classes/métodos como são declaradas (case-sensitive) o que pode causar problemas com scripts antigos que utilizavam o comportamento anterior (o nome da classe/método sempre era retornada em letras minúsculas). Uma possível solução é procurar por essas funções no seu script e utilizar a função strtolower(). Esta mudança de case-sensite change também se aplica a constantes mágicas pré-definidas __CLASS__, __METHOD__, e __FUNCTION__. Esses valores são retornadas exatamente como são declarados (case-sensitive).
  • ip2long() agora retorna FALSE quando um endereço IP inválido é passado como argumento para a funcão, e não mais -1.
  • Se existem funcões definidas no arquivo incluído, elas podem ser usadas no arquivo que a inclui independete se antes ou depois do return. Se o mesmo arquivo for incluído duas vezes, o PHP 5 emitirá um erro fatal porque as funções já foram declaradas, enquanto o PHP 4 não se importa com isso. É recomendado o uso de include_once ao invés de verificar se o arquivo já foi incluído e retornar uma condição dentro do arquivo incluído.
  • include_once e require_once primeiro normaliza o caminho para o arquivo no Windows de modo que incluir A.php e a.php incluirá somente um arquivo.
  • Passar um array para um função por valor não irá mais resetar o ponteiro interno do array para acessos na array realizados dentro da função. Em outras palavras, no PHP 4 se você passar uma array para uma função, seu ponteiro interno dentro da função será resetado, enquanto que no PHP 5, quando você passa uma array para uma função, o ponteiro dela dentro da função será o mesmo quando for passada para a função.

Exemplo #1 strrpos() e strripos() agora usam todo o texto como busca (needle)

<?php
var_dump
(strrpos('ABCDEF','DEF')); //int(3)

var_dump(strrpos('ABCDEF','DAF')); //bool(false)
?>

Exemplo #2 Um objeto sem propriedades não será mais considerado "vazio"

<?php
class test { }
$t = new test();

var_dump(empty($t)); // echo bool(false)

if ($t) {
    
// Será executado
}
?>

Exemplo #3 Em alguns casos classes devem ser declaradas antes de serem usadas

<?php

//funciona sem erros:
$a = new a();
class 
{
}


//lança um erro:
$a = new b();

interface 
c{
}
class 
implements {


?>

add a note add a note

User Contributed Notes 13 notes

up
6
john.g
19 years ago
PATH_TRANSLATED is handy when using Apache's ModRewrite engine, as it gives you the name and path of the resulting file rather than the one that was requested by the user. Since PHP 5.0 and Apache 2 no longer support this variable, I created a workaround by adding an environment variable to my ModRewrite command:

Original:
RewriteRule ^/test/(.*)\.php(.*) /test/prefix_$1.php$2

Adjusted:
RewriteRule ^/test/(.*)\.php(.*) /test/prefix_$1.php$2 [E=TARGET:prefix_$1.php]

I could then find out the resulting file name through the super global $_ENV, for instance:

<?php
echo "The actual filename is ".$_ENV['REDIRECT_TARGET'];
?>

Note: The "REDIRECT_" prefix appears to be allocated automatically by ModRewrite.
up
5
paul at oconnor-web dot net
16 years ago
The __call function will also lowercase the method arguement:

<?php
  
function __call($method, $args) {
     if (
$method == 'Foo') {
       return
true;
     } else {
       return
false
    
}
   }
?>

(= false)
up
3
Anonymous
18 years ago
is_a have been deprecated. You can simply replace all occurences with the new instanceOf operator, although this will break backwards-compatibility with php4.
up
1
Aggelos Orfanakos
16 years ago
As with array_merge(), array_merge_recursive() returns NULL in PHP 5 if a non-array parameter is passed to it.
up
1
nami
16 years ago
addition of the note on 07-Sep-2004 06:40

if you write down your code like this PHP5 will just work fine:

<?php
     $array_1
= array('key1'=>'oranges','key2'=>'apples');
    
$array_2 = array('key3'=>'pears','key4'=>'tomatoes');
    
$array_3 = array();
    
$arr_gemerged = array_merge($array_1,$array_2,$array_3);
     echo
"result:<br>";
    
print_r($arr_gemerged);
     echo
"<br>";
?>

---

so you have to declare array_3 as array() instead of NULL
up
1
cyberhorse
19 years ago
clone() is a php function now.

if you create a subclass, it no longer uses samename methods in superclass as a constructor.
up
0
kemal djakman
16 years ago
The handling of accessing empty property of a class error has also changed:
<?php

class Foo {

    var
$Bar = 'xxx';

    function
F() {
        echo
$this->$Bar;
    }
}

$Obj = new Foo();
$Obj->F();

?>

Notice the $ sign after object dereference opr?  $Bar is empty inside method F.   PHP4 would only generate a warning, PHP5 throws a fatal error
up
0
Amir Laher
17 years ago
Some other things to be aware of:

some extra strictness:
* object members can no longer be accessed using array-member syntax
* function-calls with too many arguments will now cause errors.

Also, from PHP5.2, custom session handlers are affected:
* Best not to use global objects in custom session-handling functions. These would get destructed *before* the session is written (unless session_write_close() is called explicitly).
up
0
Anonymous
19 years ago
Be careful with array_merge in PHP5.1 not only a E_WARNING is thrown, but also the result is an empty array. So if you merge two select queries and the last one is empty you will end up with no array at all.

<?php
        $array_1
= array('key1'=>'oranges','key2'=>'apples');
       
$array_2 = array('key3'=>'pears','key4'=>'tomatoes');
       
$array_3 = null;
       
$arr_gemerged = array_merge($array_1,$array_2,$array_3);
       
print_r($arr_gemerged);
        echo
"<br>";
?>

Result on php4:
Array ( [key1] => oranges [key2] => apples [key3] => pears [key4] => tomatoes )

Result on php5:
Warning: array_merge() [function.array-merge]: Argument #3 is not an array in /removed/by/danbrown/for/manual.php on line 7
up
-1
michael dot darmousseh at gmail dot com
14 years ago
Hack way to fix the array_merge problem so that it works with your existing php4 code

<?php
function array_merge5()
{
   
$args = func_get_args();
    foreach(
$args as $key=>$arg)
       
$args[$key] = (array) $arg;
    return
call_user_func_array("array_merge", $args);
}
?>

just put it somewhere completely accessible to your codebase and change all of your calls to array_merge to array_merge5.
up
-3
Sinured
16 years ago
Not mentioned above: The PHP/FI 2 function style (old_function aka cfunction) is no longer supported as of PHP 5.
up
-2
dward . maidencreek.com
19 years ago
Another change that we've had problems with while trying to use PHP4 code in PHP5 is how $this is carried across static method calls if they are not declared static in PHP5.  The main issue was that debug_backtrace() now shows the first class with -> instead of the second with :: in the backtrace element when the method in the second class was called statically (using ::) from a method in the first class.
up
-4
Steven
16 years ago
Three more that we discovered:

== 1. No longer can re-assign $this ==

The follwoing example works under PHP4 (it outputs "OK"), but produces a fatal error under PHP5:

<?php
 
class a
 
{
    var
$text;
    function
a() { $this->text = 'OK'; }
  }

  class
b
 
{
    var
$text = 'NOT OK';
    function
b() { $this = new a(); }
  }
   
 
$myClass = new b();
  echo
$myClass->text;
?>

== 2. No comments allowed after shorthand echo block ==

The follwoing example works under PHP4, but produces a sytax error under PHP5.

<?=//comment?>

== 3. Constructors return a reference as default ==

The follwoing example works under PHP4, but produces an E_NOTICE notice under PHP5.

<?php
 
class MyClass { function MyClass() { echo('OK'); } }
 
$myObj = null;
 
$myObj &= new MyClass();
?>

Removing the ampersand solves the problem
To Top