我正在编写一些伪代码来学习一些设计模式。因此,我创建了一个实现FlyBehavior
的类Duck.php
。当我调用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
来实现
或者另一种方法是使用依赖性管理,例如检查composer
<?php
require_once('FlyBehaviour.php');
class Duck implements FlyBehavior
{
public function flyWithWings(){
echo 'foo';
}
}
?>
如果你不喜欢每次手动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();
?>
现在,所有需要的类都会自动加载(当您第一次实例化它们时),这意味着您不必在脚本中手动要求任何类文件。
尝试一下;将为您节省大量时间:)