php5.4 autoloading traits

MyStream picture MyStream · May 17, 2012 · Viewed 9.2k times · Source

Are traits in php5.4 subject to autoloading?

I've not yet got an environment to test in, but I can't see any mention of it on __autoload at php.net or on the traits page, but it seems traits behave like classes in some regards.

Has anyone tried this yet?

UPDATE:

I found a request here: https://bugs.php.net/bug.php?id=61265 (2012-03-03 13:10 UTC)

that seems to suggest it does work, but not explicitly. Can anyone confirm that a straight __autoload() will be called for a missing trait?

UPDATE: Confirmed - it works as expected - __autoload will fetch traits, although getting php5.4 to work first time seems to be bigger challenge.

Thanks, MyStream

Answer

Pascal MARTIN picture Pascal MARTIN · May 17, 2012

According to the manual, the trait_exists() function takes a boolean as second parameter, that is related to autoloading; which seems to indicate that traits and autoload are not two incompatible ideas.

In addition, if you take a look at the source-code of that trait_exists() function, you'll see a section of code, conditioned by that second parameter, that looks quite similar to what you can see in the source-code of class_exists().
So, I'd say a second time that traits and autoload are not incompatible ideas ;-)

(I don't have PHP 5.4 installed on my current computer, so I cannot test by myself -- but, looking at the code...)



[edit] OK, I've just compiled PHP 5.4.3, the current stable version:

$ /usr/local/bin/php --version
PHP 5.4.3 (cli) (built: May 17 2012 21:11:42)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies

Let's try the following short portion of code, which is saved as temp-2.php, and tries to use a trait that is not declared in this file:

spl_autoload_register(function ($name) {
    echo "AUTOLOAD :: ";
    var_dump($name);
});

class MyClass {
    use MyTrait;   // Let's try to use a trait that is not declared in this file
}

$obj = new MyClass();
$obj->plop();

Basically, if autoloading works for traits, "AUTOLOAD" and the name of my trait should be displayed.

So, let's try executing that portion of code -- and here is the result I get:

$ /usr/local/bin/php ./temp-2.php
AUTOLOAD :: string(7) "MyTrait"

Fatal error: Trait 'MyTrait' not found in /.../temp-2.php on line 13

So, the autoloading function (here, an anonymous one -- but that doesn't change a thing) is called...
... which means that traits are, with PHP 5.4.3, subject to autoloading.