Skip to content

Instantly share code, notes, and snippets.

@bdelespierre
Forked from bwoebi/scala_traits_with_php.php
Last active December 27, 2015 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdelespierre/7341658 to your computer and use it in GitHub Desktop.
Save bdelespierre/7341658 to your computer and use it in GitHub Desktop.
<?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();
<?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
);
});
<?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