I was wondering what the static
keyword returns in a trait? It seems like it's being bound to the trait and not the class that uses it. For example:
trait Example
{
public static $returned;
public static function method()
{
if (!eval('\\'.get_called_class().'::$returned;')) {
static::$returned = static::doSomething();
}
return static::$returned;
}
public static function doSomething()
{
return array_merge(static::$rules, ['did', 'something']);
}
}
class Test {}
class Test1 extends Test
{
use Example;
protected static $rules = ['test1', 'rules'];
}
class Test2 extends Test
{
use Example;
protected static $rules = ['test2', 'rules'];
}
// usage
Test1::method();
// returns expected results:
// ['test1', 'rules', 'did', 'something'];
Test2::method();
// returns unexpected results:
// ['test1', 'rules', 'did', 'something'];
// should be:
// ['test2', 'rules', 'did', 'something'];
I could get it work with some nasty eval()
in the method()
method:
public static function method()
{
if (!eval('\\'.get_called_class().'::$returned;')) {
static::$returned = static::doSomething();
}
return static::$returned;
}
Now it simply matches it against \My\Namespaced\Class::$returned
but it is also weird as as checking a static property, $returned
, which was defined in the trait to begin with and was bound correctly to the class that uses it. Then why won't the static::$returned
work?
The PHP version is 5.6.10.