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();
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.
Scala traits don't allow constructor parameters However, be aware that a class can extend only one abstract class.
Traits can not implement interfaces. A trait allow both classes to use it for common interface requirement. It supports the use of abstract methods.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With