我正在编写一些虚拟代码来学习一些设计模式。因此,我创建了一个实现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';
答案 0 :(得分:0)
你的问题是你没有在实现它的类中包含接口,你可以通过require_once
或者替代方法是使用依赖关系管理,例如检查composer
<?php
require_once('FlyBehaviour.php');
class Duck implements FlyBehavior
{
public function flyWithWings(){
echo 'foo';
}
}
?>
答案 1 :(得分:0)
如果你不想每次都手动require
/ include
所有类库 - 就像我一样;或许你可能感兴趣__autoload
:
http://www.php.net/manual/en/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();
?>
现在,所有必需的类都会自动加载(当你第一次实例化时) - 这意味着你不必在脚本中手动要求任何类文件。
尝试一下;将为您节省大量时间:)