-
-
Save bdelespierre/7341658 to your computer and use it in GitHub Desktop.
This file contains hidden or 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($classname) { | |
if (strpos($classname, '\\with') === false) | |
return false; | |
list($namespace, $class) = str_split($classname, strrpos($classname, '\\')); | |
$class = substr($class, 1); | |
$parts = explode('\\with', $classname); | |
$base = '\\' . trim(array_shift($parts), '\\'); | |
if (empty($parts)) | |
return false; | |
$use = ''; | |
foreach($parts as $part) | |
$use .= "use $part; "; | |
eval("namespace $namespace { class $class extends $base { $use } }"); | |
}); | |
class a {} | |
trait b { static function hello() { echo "Hello!"; } } | |
trait c {} | |
use \a\with\c\with\b as _; | |
_::hello(); |
This file contains hidden or 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 hidden or 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