php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #70783 Adding a trait to a class produces fatal error
Submitted: 2015-10-25 13:11 UTC Modified: 2015-10-27 07:59 UTC
From: joel at kociolek dot org Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.6.14 OS: Linux / Ubuntu 14.04
Private report: No CVE-ID: None
 [2015-10-25 13:11 UTC] joel at kociolek dot org
Description:
------------
I had perfectly working code. I added a trait to one of the classes and it started to produce fatal errors. I tried to cut down the complexity of the code and made the simplest example that I could do. See below.


Test script:
---------------
<?php
class B extends A {}
trait wtf {}
class A {
  use wtf;
}
echo "OK\n";


Expected result:
----------------
Should display OK


Actual result:
--------------
Displays:

Fatal error: Class 'A' not found in /home/joel/php-5.6.14/test.php on line 2



Please note that removing the "use" line from the sample code above makes it work (It display "OK").


Patches

Add a Patch

Pull Requests

Pull requests:

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-10-26 19:10 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2015-10-26 19:10 UTC] requinix@php.net
While classes can often be used before they are "defined" (in terms of where they are located in a file), this does not apply once you introduce traits. With traits, classes must be defined before they are used. Which is a good thing to do regardless.

trait wtf {}
class A {
  use wtf;
}
class B extends A {}
 [2015-10-27 07:59 UTC] joel at kociolek dot org
-Type: Bug +Type: Documentation Problem
 [2015-10-27 07:59 UTC] joel at kociolek dot org
Ok. I understand that classes should be defined before they are used. However there still may be a documentation bug and/or a missing warning.

I found in the doc at http://php.net/manual/en/language.oop5.inheritance.php that "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."

This doesn't seem to be strictly true. According to the doc, my working code shouldn't work! And the fact that traits change the strictness with which PHP parses classes doesn't seem to be explained anywhere, or at least I couldn't find it in the docs.

Moreover, shouldn't there be a warning when classes are used before they are defined?

I would happily send a doc patch and/or a failing test for that (potentially) missing warning, if you'd tell me that it is legit and guide me just a little bit as to where it should go (in the doc and/or test suite).

Thanks.
 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Wed Jun 19 10:01:27 2019 UTC