Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute constructor in trait

Tags:

php

traits

I wan't to execute constructor in my trait (or another method while trait is used). Is it possible?

trait test{
    public function __construct()
    {
        echo 'test';
    }
}

class myClass{
    use test;
    public function __construct(){
        echo 'myClass';
    }
}
new myClass();
like image 893
Bolek Lolek Avatar asked Dec 18 '17 10:12

Bolek Lolek


People also ask

Can I use constructor in trait?

Unlike traits in Scala, traits in PHP can have a constructor but it must be declared public (an error will be thrown if is private or protected). Anyway, be cautious when using constructors in traits, though, because it may lead to unintended collisions in the composing classes.

Can Scala trait have constructor?

Scala traits don't allow constructor parameters However, be aware that a class can extend only one abstract class.

Can trait implement interface?

Traits can not implement interfaces. A trait allow both classes to use it for common interface requirement. It supports the use of abstract methods.

Can we instantiate trait in PHP?

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own.


1 Answers

Try it like this (test):

trait test{
    public function __construct()
    {
        echo 'test';
    }
}

class myClass{
    use test {
        test::__construct as private __tConstruct;
    }
    public function __construct(){
        $this->__tConstruct();
    }
}
new myClass();
like image 153
Claudio Avatar answered Sep 28 '22 03:09

Claudio