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';
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';
}
}
?>
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
Ie 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 :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.