Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 5.4 - Traits and self / static

I want to chain method calls on my classes as follows :

new Obj($args, $if, $any)->foo()->bar();

Unfortunatly i have to enclose the construction within parenthesis :

(new Obj($args, $if, $any))->foo()->bar();

So i would like to have a trait that i could reuse in every class i want to be able to do something like :

Obj::create($args, $if, $any)->foo()->bar();

I want it to be a trait so my classes can still inherit from other classes. I've come to that point :

trait Create
{
    public static final function create()
    {
        $reflect = new ReflectionClass(/* self ? static ? Anything else ? */);
        return $reflect->newInstanceArgs(func_get_args());
    }
}

class Obj
{
    use Create;

    // ...
}

But it seems like traits don't handle self or static keywords, and i can't do get_class($this) since this is static. Is there a clear way to do what i want please ?

Thanks for reading.

EDIT : For those who wonder, here is why i want it to be a trait and not an abstract base class :

$database = (new Database())
    ->addTable((new Table())
        ->addColumn((new Column('id', 'int'))
            ->setAttribute('primary', true)
            ->setAttribute('unsigned', true)
            ->setAttribute('auto_increment', true))
        ->addColumn(new Column('login', 'varchar'))
        ->addColumn(new Column('password', 'varchar')));

$database = Database::create()
    ->addTable(Table::create()
        ->addColumn(Column::create('id', 'int')
            ->setAttribute('primary', true)
            ->setAttribute('unsigned', true)
            ->setAttribute('auto_increment', true))
        ->addColumn(Column::create('login', 'varchar'))
        ->addColumn(Column::create('password', 'varchar')));

Less bracket depth, less mistakes, and less time needed to fix these mistakes, plus an easier to read code, and, in my opinion, a better looking code.

like image 563
Virus721 Avatar asked Mar 15 '13 23:03

Virus721


1 Answers

Yes, there is get_called_class(), which does exactly what you want.

like image 56
Fabian Schmengler Avatar answered Sep 23 '22 00:09

Fabian Schmengler