Traits



objects Attributes ( traits ) are code designed for re-use in classes structures providing multiple classes. It is designed to reduce single inheritance limitations by making it possible to freely reuse method and attribute clusters independently within different classes. It also opens up multiple inheritance by reducing code complexity inside. Object qualities are similar to classes but can not be exemplified as classes. 

 

 

 

The characteristics of Objective Qualities are;

Can only be used with classes.
● They may use the same qualities and methods in multiple classes.
Reduce code complexity by grouping methods. 
● They can not be sampled as classes.
Treat what they are involved as part of the class.
● They may contain interface.

 

 

# Syntax


The semantics of object properties are similar to the syntax of classes, but the trait statement is used instead of class .

<?php trait ExampleTraitName
{
     # Nitelik ve yöntemler
}

 

 

# Create Objective Trait


object qualities are constructed with content as shown in the syntax above.

File: InfoTrait.php
<?php trait InfoTrait
{
    protected $errors = [];

    public function setError(string $error)
    {
        $this->errors[] = $error;
    }

    public function getErrors() : array
    { 
        return $this->errors;
    }   
}

We have created the qualities and methods to be used for the same purpose in many classes above. The greatest benefit to us of object qualities is that written object clusters can be used in any desired class. 

 

 

# Use Object Qualities


We will use the trait file that we created for the example above, we include it in the class access area by specifying it with use .

File: Automobile.php
<?php class Automobile
{
    use InfoTrait;

    protected $wheel;

    public function setWheelCount(int $wheel)
    {
        $this->wheel = $wheel;

        if( $this->wheel > 4 )
        {
            $this->setError('Invalid wheel count['.$this->wheel.']');
        }
    }

    public function getWheelCount() : int
    {
        return $this->wheel;
    }
}

Let's use objective methods that we have described above in our Automobile :: class.

File: index.php
<?php require 'InfoTrait.php'; require 'Automobile.php';

$automobile = new Automobile;

$automobile->setWheelCount(5);

var_dump($automobile->getErrors());
array ( 1 ) {[0] => string ( 22 ) "Invalid wheel count [5]"}

object qualities act as part of the classes they call.

<?php trait InfoTrait
{
    protected $errors = [];

    public function getClassName()
    {
        return __CLASS__;
    }

    public function setError(string $error)
    {
        $this->errors[] = $error;
    }

    public function getErrors() : array
    { 
        return $this->errors;
    }   
}
<?php require 'InfoTrait.php'; require 'Automobile.php';

$automobile = new Automobile;

echo $automobile->getClassName();
Automobile