[PHP-users 34128] クラスの宣言について
Michael
michael @ midnight-party.net
2008年 11月 13日 (木) 02:30:06 JST
神崎と申します。
下記のような簡単なクラスを作ってみたところ、
A
Fatal error: Cannot redeclare class Pub_Class in H:\xampp\htdocs\classtest\b.class.php on line 3
のエラーになります。
Pub_Classが再宣言できないとのことです。
a.class.phpとb.class.phpはある事情からファイル名が違うだけで、
クラス名や関数名は同じです。
自分の中ではindex.phpのループの中で毎回クラスをnewしており、
なおかつmain.class.phpの中でも新たにnewしているので、
「AB」と表示されると思ったのですがエラーになりました。
但し、1回目のループはちゃんと処理され「A」と表示されますが、
2回目のループでエラーになるようです。
ちなみにmain.class.phpの
$a = array( "./a.class.php", "./b.class.php" );
を
$a = array( "./a.class.php", "./a.class.php" );
に変えると正常に動作し、表示は「AA」となります。
PHPのバージョンは「PHP Version 5.2.6」です。
OSはWindows XP SP3ですが、Linuxで試したところ
やはり同様のエラーになってしまいました。
原因がおわかりになる方、教えていただけませんでしょうか。
よろしくお願いいたします。
index.phpをまず最初にブラウザからアクセスします。
---index.php-----------------------
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Class Test</title>
</head>
<body>
<?php
include_once( "./main.class.php" );
for( $i = 0; $i < 2; $i++ ) {
$a = new Get_Main();
$a->Call_Class( $i );
}
?>
</body>
</html>
-----------------------------------
---main.class.php------------------
<?php
class Get_Main
{
public function Call_Class( $n )
{
$a = array( "./a.class.php", "./b.class.php" );
// $a = array( "./a.class.php", "./a.class.php" );
include_once( "{$a[$n]}" );
$b = new Pub_Class();
}
}
?>
-----------------------------------
---a.class.php---------------------
<?php
class Pub_Class
{
function __construct()
{
print "A";
}
}
?>
-----------------------------------
---b.class.php---------------------
<?php
class Pub_Class
{
function __construct()
{
print "B";
}
}
?>
-----------------------------------
PHP-users メーリングリストの案内