ホーム > php > PHP5.3.0~2の罠

PHP5.3.0~2の罠

PHP5.3.3では以下のような「後方非互換の変更」が加えられています。

Methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn’t affect non-namespaced classes.

<?php
namespace Foo;
class Bar {
    public function Bar() {
        // treated as constructor in PHP 5.3.0-5.3.2
        // treated as regular method in PHP 5.3.3
    }
}
?>

There is no impact on migration from 5.2.x because namespaces were only introduced in PHP 5.3.
PHP 5.3.3 Released!

どういう事かというと、

<?php
class A
{
  function A()
  {
    echo __CLASS__;
  }
}
class B extends A
{
}
class C extends B
{
  function C()
  {
    parent::B();
  }
}
new C();

結果
PHP5.3.2

PHP Fatal error:  Call to undefined method B::B()

PHP5.3.3

A

PHP5.3.xによってPHP4に対する後方互換が崩れたんですが、PHP5.3.3でPHP5.3.x非互換となる代わりにPHP4後方互換が一部戻ったという話。
PEAR::Image_Graphで問題でてました。
PHP5の環境なら以下のように書くので問題は起こらないんですけどね。

<?php
class A
{
  public function __construct()
  {
    echo __CLASS__;
  }
}
class B extends A
{
}
class C extends B
{
  public function __construct()
  {
    parent::__construct();
  }
}
new C();
カテゴリー: php タグ: ,
  1. コメントはまだありません。
  1. トラックバックはまだありません。