php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #68936 If class uses trait, it is not loaded after any global code that precedes it
Submitted: 2015-01-28 17:44 UTC Modified: 2015-01-28 20:04 UTC
From: jevgenijs at zini dot lv Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 5.5.21 OS: Linux
Private report: No CVE-ID: None
 [2015-01-28 17:44 UTC] jevgenijs at zini dot lv
Description:
------------
Normally, if file c.php contains class definition, the class is loaded before any global code in file c.php is executed. However, it is not true if class uses trait.

If I remove "use C;" from the example below, the code passes.

Test script:
---------------
==== ./a.php ====
<?php
require_once 'c.php';

==== ./c.php ====
<?php
require_once 'b.php';
trait C {}
class A {
        use C;
}

==== ./b.php ====
<?php
require_once 'c.php';
class B extends A{}

php -f a.php

Expected result:
----------------
no error

Actual result:
--------------
PHP Fatal error:  Class 'A' not found in /www/htdocs/www.zini.lv/develjonas/tmp/b.php on line 3

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-01-28 20:04 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2015-01-28 20:04 UTC] requinix@php.net
That's right.

I'm not actually aware of any place in the documentation that says classes are available to use before they are defined - same file or not. In fact, the closest I can get is the note on the Object Inheritance page which says the opposite:

  Unless autoloading is used, then classes must be defined before they are used.
  If a class extends another, then the parent class must be declared before the
  child class structure. This rule applies to classes that inherit other classes
  and interfaces.

http://php.net/manual/en/language.oop5.inheritance.php

Yes, I know that in practice simple classes can be defined automatically by merely being contained in a file, but as far as I can tell that's unofficial and undocumented behavior so you shouldn't depend on that. And here is one place where that won't work.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Apr 29 18:01:30 2024 UTC