[英]Getting a 500 internal server error when implementing interface
我正在編寫一些虛擬代碼來學習一些設計模式。 因此,我做了一個類Duck.php
實現FlyBehavior
。 當我調用index.php
,我看到一個空白頁,控制台告訴我,有一個500 Internal Server Error
。 如果我不贊成implenets FlyBehavior
,則錯誤消失。 所以我想我缺少有關如何正確實現接口的信息。 謝謝!
PHP 5.4.10
Duck.php
<?php
class Duck implements FlyBehavior
{
public function flyWithWings(){
echo 'foo';
}
}
FlyBehavior.php
<?php
interface FlyBehavior {
public function flyWithWings();
}
index.php
<?php
ini_set('error_reporting', E_ALL);
include 'Duck.php';
$duck = new Duck();
echo '<br>Test';
您的問題是您沒有在實現該接口的類中包含該接口,可以通過require_once
做到這一點。
或替代方法是使用依賴項管理,例如check composer
<?php
require_once('FlyBehaviour.php');
class Duck implements FlyBehavior
{
public function flyWithWings(){
echo 'foo';
}
}
?>
如果你恨不必require
/ include
手動每次都類庫-像我這樣做; 也許__autoload
可能會讓您感興趣:
http://www.php.net/manual/zh/function.autoload.php
像這樣設置腳本:
/ index.php
/ libs / FlyBehavior.php
/ libs / Duck.php
即將所有類放在名為libs
的文件夾中,然后在index.php上設置audoloader
因此,您的index.php將如下所示:
<?php
// Constants
define('CWD', getcwd());
// Register Autoloader
if (!function_exists('classAutoLoader')) {
function classAutoLoader($class) {
$classFile = CWD .'/libs/'. $class .'.php';
if (is_file($classFile) && !class_exists($class))
require_once $classFile;
}
}
spl_autoload_register('classAutoLoader');
// Rest if your script
ini_set('error_reporting', E_ALL);
ini_set('display_error', 'On');
// Test
$duck = new Duck();
$duck->flyWithWings();
?>
現在,所有必需的類都將自動加載(第一次實例化它們時)-這意味着您不必在腳本中手動要求任何類文件。
試試看; 將為您節省大量時間:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.