假設我們共有三支程式 index.php、1.php、2.php 語法如下:
1.php
<?php
class hello {
public function hi() {
echo 'Hi 111';
}
}
2.php
<?php
class hello {
public function hi() {
echo 'Hi 222';
}
}
index.php
<?php
include '1.php';
include '2.php';
$a = new hello();
$a->hi();
當我們執行 index.php 時,很顯然會出錯,因為class的名稱(hello)重複了,這時候就要透過命名空間來解決,修改方式如下...
1.php
<?php
namespace name1;
class hello {
public function hi() {
echo 'Hi 111';
}
}
2.php
<?php
namespace name2;
class hello {
public function hi() {
echo 'Hi 222';
}
}
index.php
<?php
include '1.php';
include '2.php';
$a = new name1\hello();
$a->hi();
這樣就能順利印出 "Hi 111" 了
No comments:
Post a Comment