Frage

I'm writing some dummy code to learn some design patterns. Therefore I made a class Duck.php that implements FlyBehavior. When I call the index.php, I see a blank page, and the console tells me, there is a 500 Internal Server Error. If I outcomment implenets FlyBehavior, the error disappears. So I guess I'm missing something about how to correctly implement an interface. Thank you!

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';
War es hilfreich?

Lösung

Your problem is that you didn't include the interface in the class that implements it, you can do that by require_once

Or an alternate to this is to use dependency management , for example check composer

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

class Duck implements FlyBehavior
{

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

Andere Tipps

If you hate having to require/include all the class library every time manually - like I do; perhaps __autoload may be of interest to you:

http://www.php.net/manual/en/function.autoload.php

Setup your scripts like this:

/ index.php
/ libs / FlyBehavior.php
/ libs / Duck.php

I.e. place all your classes in a folder called libs and then setup audoloader on index.php

So, your index.php will look like this:

<?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();

?>

Now, all the required classes are automatically loaded (when you instantiate them for the first time) - meaning you don't have to require any of the class files manually in your script.

Try it out; will save you tons of time :)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top