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