【问题标题】:Getting a 500 internal server error when implementing interface实现接口时出现 500 内部服务器错误
【发布时间】:2014-04-29 08:32:54
【问题描述】:

我正在编写一些虚拟代码来学习一些设计模式。因此我创建了一个实现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';

【问题讨论】:

  • 检查Duck.php是否在同一个目录中。当所有东西放在一起时,代码工作正常。 eval.in/143641
  • 你必须包含FlyBehavior.php

标签: php interface


【解决方案1】:

您的问题是您没有在实现它的类中包含接口,您可以通过require_once 来做到这一点

或者替代方法是使用依赖管理,例如检查composer

<?php
require_once('FlyBehaviour.php');

class Duck implements FlyBehavior
{

public function flyWithWings(){
      echo 'foo';
    }
}
?>

【讨论】:

  • -.- 谢谢,这对我来说真的很明显。
【解决方案2】:

如果您讨厌每次都手动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();

?>

现在,所有必需的类都会自动加载(当您第一次实例化它们时)——这意味着您不必在脚本中手动要求任何类文件。

试试看;将为您节省大量时间:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-05
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多