开发者

PHP interface problem - class not found

开发者 https://www.devze.com 2023-01-16 13:33 出处:网络
Hi I have a very simple class that implements an interface.Both the class and the interface are in the same file.

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 imple开发者_如何学Goments 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;
    }
}


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)


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


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...


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

0

精彩评论

暂无评论...
验证码 换一张
取 消