Skip to content

Instantly share code, notes, and snippets.

@bwoebi
Last active December 27, 2015 11:39
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bwoebi/7319798 to your computer and use it in GitHub Desktop.
Save bwoebi/7319798 to your computer and use it in GitHub Desktop.
<?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"
}
*/
@bdelespierre
Copy link

I came up with a different version which is not recursive: https://gist.github.com/bdelespierre/7341658

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment