Last active
December 27, 2015 11:39
-
-
Save bwoebi/7319798 to your computer and use it in GitHub Desktop.
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 | |
spl_autoload_register(function ($name) { | |
// $exp will be the name of the class without the \with\traitname part => array_splice | |
$exp = explode("\\", $name); | |
// serach from end | |
$index = array_search("with", array_reverse($exp, true)); | |
if (!$index || $index - 1 == count($exp)) // also fail when value is 0 | |
return false; | |
$beginning = $exp; | |
$last = array_pop($beginning); | |
$beginning = implode("\\", $beginning); | |
$end = array_splice($exp, $index); | |
array_shift($end); // remove the "with" | |
$trait = "\\".implode("\\", $end); | |
$full = ($exp[0]?"\\":"").implode("\\", $exp); | |
eval( | |
<<<PHP | |
namespace $beginning; | |
class $last extends $full { | |
use $trait; | |
} | |
PHP | |
); | |
}); |
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 | |
namespace space { | |
trait e { | |
public $f = "f"; | |
} | |
} | |
namespace { | |
include 'scala_traits_with_php.php'; | |
class a { | |
public $b = "b"; | |
} | |
trait c { | |
public $d = "d"; | |
} | |
$obj = new a\with\c\with\space\e; | |
var_dump($obj); | |
} | |
/* | |
Output: | |
object(a\with\c\with\space\e)#2 (3) { | |
["b"]=> | |
string(1) "b" | |
["d"]=> | |
string(1) "d" | |
["f"]=> | |
string(1) "f" | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I came up with a different version which is not recursive: https://gist.github.com/bdelespierre/7341658