Table of Contents
📖 2 minutes read
I was refactoring some code and extracting a common method into a trait. I added use HasProductMapping; to 15+ plugin classes—then got this error:
Trait method getProductMapping has not been applied as App\Plugins\BasePlugin::getProductMapping
has the same visibility and finality
What happened? Some of those plugins extended BasePlugin, which already had use HasProductMapping;. I was adding the trait to both parent and child classes, causing a conflict.
The Problem with Inheritance + Traits
When you add a trait to a class hierarchy, PHP doesn’t automatically deduplicate. If both parent and child use the same trait, you’ll get duplicate method declarations:
// Parent class
class BasePlugin
{
use HasProductMapping; // ✅ Trait added here
}
// Child class
class GoogleToursPlugin extends BasePlugin
{
use HasProductMapping; // ❌ ERROR! Parent already has this trait
}
The Fix
Before adding a trait to a class, check the inheritance chain:
- Does the parent class already use this trait? If yes, skip it—child inherits automatically.
- Do any base classes higher up the chain use it? Same rule applies.
In my case, the correct approach was:
// ✅ Add trait ONLY to base classes that don't inherit it
class BasePlugin
{
use HasProductMapping; // Parent has it
}
class GoogleToursPlugin extends BasePlugin
{
// No trait needed—inherited from BasePlugin
}
class StandalonePlugin // Doesn't extend BasePlugin
{
use HasProductMapping; // ✅ Needs it directly
}
Quick Check
When adding a trait across many classes:
- Group by parent class
- Add trait to parent or children, never both
- If a standalone class exists (no parent with the trait), add it there
This saves you from duplicate declaration errors and keeps your trait usage clean.
Leave a Reply