Trait is a concept of OOP. Where you can add methods, properties, or any other code that you want to reuse across multiple classes.
After that you can use those functions into other classes by using a keyword use
.
Create a new PHP file for your trai wiyh .php extension and follow the naming convention of customTraitName.php.
Define your trait on trait file and define your trait using the trait keyword. You can add methods, properties.
app/Traits/customTrait.php
namespace App\Traits;
trait customTrait
{
public function yourFunction()
{
// Your code here
}
public function yourAnotherFunction()
{
// Your code here
}
}
Now go you your class where you want to access those methods, properties. call use customTrait
after you class starts.
use App\Traits\customTrait;
class YourClass
{
use customTrait;
public function someMethod()
{
// Now you can call those methods, properties with this-> instance -
$this->yourFunction();
}
}
Top comments (0)