Last active
January 24, 2018 07:23
-
-
Save Glutexo/f0fb3d5fadd8958791c0890c8bd93f96 to your computer and use it in GitHub Desktop.
Demonstration of a strange PHP behavior concerning class definition order when nested traits are used
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MyClass | |
{ | |
use MyFirstTrait; | |
} | |
// This does not work. MyFirstTrait should use MySecondTrait, "Fatal error: | |
// Trait 'MyFirstTrait' not found" is raised instead. | |
trait MyFirstTrait | |
{ | |
use MySecondTrait; | |
/** | |
* @return string | |
*/ | |
public function first(): string | |
{ | |
return __METHOD__; | |
} | |
} | |
trait MySecondTrait { | |
/** | |
* @return string | |
*/ | |
public function second(): string | |
{ | |
return __METHOD__; | |
} | |
} | |
$myInstance = new MyClass; | |
var_dump($myInstance->first()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// This works. The use clause in MyFirstTrait is commented out, only one trait | |
// is used. | |
class MyClass | |
{ | |
use MyFirstTrait; | |
} | |
trait MyFirstTrait | |
{ | |
// use MySecondTrait; | |
/** | |
* @return string | |
*/ | |
public function first(): string | |
{ | |
return __METHOD__; | |
} | |
} | |
trait MySecondTrait { | |
/** | |
* @return string | |
*/ | |
public function second(): string | |
{ | |
return __METHOD__; | |
} | |
} | |
$myInstance = new MyClass; | |
var_dump($myInstance->first()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// This works. MyClass is now defined after the traits. | |
trait MyFirstTrait | |
{ | |
use MySecondTrait; | |
/** | |
* @return string | |
*/ | |
public function first(): string | |
{ | |
return __METHOD__; | |
} | |
} | |
trait MySecondTrait { | |
/** | |
* @return string | |
*/ | |
public function second(): string | |
{ | |
return __METHOD__; | |
} | |
} | |
class MyClass | |
{ | |
use MyFirstTrait; | |
} | |
$myInstance = new MyClass; | |
var_dump($myInstance->first()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment