我有一個PHP接口編碼問題。我從「Head First Design Patterns」一書中讀取了Java代碼,並將其轉換爲下面的代碼。我正在使用MAMP/PHP 5.6.2和NetBeans 8.1。PHP接口編碼
我想在擴展抽象類(MenuComponent)的Menu類中實現接口「TestInterface」。 Menu類不會以「TestInterface」實現開始。代碼運行時,我將Menu類聲明中的「TestInterface」註釋爲下面的代碼;而當「TestInterface」被註釋掉時,PHP甚至在聲明接口並將接口函數保持爲Menu成員函數時也不會引發錯誤。已經成功運行簡單的代碼,同時使用上述同一平臺進行擴展和實現。由於代碼簡單的成功,我相信在我的代碼中存在結構或語法錯誤,希望有人能幫我找到什麼我提前做錯了。謝謝你。
<?php
$run = new myclass;
$run->main();
class myclass {
private $pancakeHouseMenu;
private $allMenus;
private $waitress;
public function main(){
echo "<br />hi main!<br />";
$this->pancakeHouseMenu = new Menu("PANCAKE HOUSE MENU", "Breakfast");
$this->allMenus = new Menu("ALL MENUS", "All menus combind");
$this->allMenus->add($this->pancakeHouseMenu);
$this->pancakeHouseMenu->add(new MenuItem(
"Regular Pancake Breakfast",
"Pancakes with eggs and sausage"));
$this->waitress = new Waitress($this->allMenus);
$this->waitress->printMenu();
}
}
interface TestInterface {
public function interfaceTest();
}
abstract class MenuComponent {
public function add(MenuComponent $newMenuComponent) {
throw new InvalidArgumentException("Exception thrown");
}
public function getName() {
throw new InvalidArgumentException("Exception thrown");
}
public function getDescription() {
throw new InvalidArgumentException("Exception thrown");
}
public function printOut() {
throw new InvalidArgumentException("Exception thrown");
}
}
class Waitress {
private $allMenus;
public function __construct(MenuComponent $allMenus) {
$this->allMenus = $allMenus;
$this->allMenus->add($allMenus);
}
public function printMenu() {
$this->allMenus->printOut();
}
}
class MenuItem extends MenuComponent {
private $name;
private $description;
public function __construct($name, $description) {
$this->name = $name;
$this->description = $description;
}
public function getName() {
return $this->name;
}
public function getDescription() {
return $this->description;
}
public function printOut() {
print(" " . $this->getName());
print(" -- " . $this->getDescription());
}
}
class Menu extends MenuComponent /*** implements TestInterface ***/ {
private $menuComponents = array();
private $name;
private $description;
// private $testVar;
public function __construct($name, $description) {
$this->name = $name;
$this->description = $description;
$this->testVar = "Interface test succeeded";
}
public function interfaceTest(){
return $this->testVar;
}
public function add(MenuComponent $newMenuComponent) {
array_push($this->menuComponents, $newMenuComponent);
}
public function getName() {
return $this->name;
}
public function getDescription() {
return $this->description;
}
public function printOut() {
print("<br />" . $this->getName());
print(", " . $this->getDescription());
print("<br />---------------------");
print("<br />Testing interface var: ". $this->interfaceTest());
}
}
?>
請添加菜單類爲(和接口)是什麼相關) – JimL