Skip to content

Class that uses a trait is not found when instantiated before its declaration #24519

Open

Description

@sybrew

Description

This is the same report as bugs.php.net #75771, which is still open.

The following code:

<?php

new A; // good.
new B; // fatal error.

class A {
	function __construct() {
		echo "constructed A\n";
	}
}

class B {
	use T;

	function __construct() {
		echo "constructed B\n";
		$this->traitfunc();
	}
}

new B; // good.

trait T {
	function traitfunc() {
		echo "traitfunc called\n";
	}
}

Resulted in this output:

constructed A

Fatal error: Uncaught Error: Class "B" not found in /mnt/c/Users/sybre/AppData/Local/Temp/bug75771.php:3
Stack trace:
#0 {main}
  thrown in /mnt/c/Users/sybre/AppData/Local/Temp/bug75771.php on line 3

But I expected this output instead:

constructed A
constructed B
traitfunc called

PHP Version

PHP 8.5.12 (cli) (built: Oct 21 2026 22:48:15) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.5.12, Copyright (c) Zend Technologies
    with Zend OPcache v8.5.12, Copyright (c), by Zend Technologies

Operating System

Ubuntu 24.04 (WSL2). Also reproduced on PHP 8.4.4 on Windows.

Activity

  1. NickSdot commented on Oct 23, 2026

    @NickSdot
    Contributor

    Not a bug, intentional limitation. Applies to interface- and trait-using classes. Same category as this and this, which are WONTFIX. Source ref: here and here.

    More context:
    https://www.npopov.com/2021/10/20/Early-binding-in-PHP.html

    Perhaps worth to document this better. Maybe you want to consider closing this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions