Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP interface problem - class not found

Tags:

php

interface

Hi I have a very simple class that implements an interface. Both the class and the interface are in the same file.

When I implement the interface I get a fatal error "Class not found", but when I remove the implements and then try to use the class I can use it fine???

Can anyone offer any advice on this?

Sorry here is some code that I am using to test at the moment:

$tester = new TypeOneTester();
$tester->test("Hello");

interface iTestInterface
{
    public function test($data);
}

class TypeOneTester implements iTestInterface
{
    public function test($data)
    {
        return $data;
    }
}
like image 459
David Avatar asked Sep 13 '10 22:09

David


4 Answers

Create an instance of your class after the class and the interface are defined, not before.

The order of definition in this case should be:

  1. Interface
  2. Class
  3. Instance of Class (objects)
like image 110
Jacob Relkin Avatar answered Nov 17 '22 05:11

Jacob Relkin


This is a (very poorly) documented limitation:

http://php.net/manual/pl/migration5.incompatible.php

In some cases classes must be declared before use. It only happens if some of the new features of PHP 5 (such as interfaces) are used. Otherwise the behaviour is the old.

I've filed a bug report nonetheless. IMO it should be fixed as it's inconsistent behaviour and the error message is not helpful for anyone who assumes as I did that PHP simply didn't care where you declare functions/classes. Come on, it's been there for over 10 years now...

https://bugs.php.net/bug.php?id=69665

like image 30
Mikkel Avatar answered Nov 17 '22 07:11

Mikkel


smells like a bug in php. Make sure it's reproducible with the latest version and post to bugs.php.net.

Reproduce code

interface I {}

$a = new A;
$b = new B;

class A {
    function __construct() { echo 'A'; }
}

class B implements I {
    function __construct() { echo 'B'; }
}

Expected

AB

Actual:

A
Fatal error: Class 'B' not found...
like image 3
user187291 Avatar answered Nov 17 '22 06:11

user187291


That is because, php loading interface, and instantiate class class class object where there is a certain order and must be in a Php file, if the file is not in accordance with an order of 1. Require_one interface, 2. Require_one class

like image 2
qiyulin Avatar answered Nov 17 '22 07:11

qiyulin