Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php

How to resolve naming conflicts in traits?

Hunain Tahir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Traits allow us to group methods and functionalities together in a set of reusable code. Traits are similar to classes but can not be instantiated into objects.

Note: To learn more about traits in PHP, click here.

You can inherit from multiple traits by providing a comma-separated list before the use keyword.

Sometimes, inserting multiple traits in a class can cause naming conflicts. This happens because of sharing the same signature by different methods from different traits, and as a result, a fatal error is encountered.

We can use insteadof and as operators to resolve such issues explicitly.

Conflict resolution

Choose one of the colliding functions explicitly using insteadof operator.

Basic syntax

Trait1::myfunction insteadof Trait2;

This will choose myfunction from Trait1 over Trait2.

Running example

<?php
trait Trait1 {
public function myfunction() {
echo "Hello World! \n";
}
}
trait Trait2 {
public function myfunction() {
echo "Hello Trait\n";
}
}
trait Trait3 {
public function myfunction() {
echo "Hello!\n";
}
}
class HelloFromTrait {
use Trait1, Trait2, Trait3 {
Trait1::myfunction insteadof Trait2,Trait3;
Trait2::myfunction as helloTrait;
}
}
$t = new HelloFromTrait();
$t->myfunction();
$t->helloTrait();
?>
Conflict resolution with insteadof operator

Explanation

  • We have resolved the conflict by choosing myfunction of Trait1 on line 22.

  • On line 23 we have given an alias to myfunction of Trait2 and it can be used under name helloTrait on line 29.

  • Notice that myfunction from Trait3 is not accessible. It can also be accessed by use as in similar manner.

Note: The as operator does not change the method’s signature but only assigns an alternative alias to it. So your implementation for the rest of the code will not be affected.

RELATED TAGS

php

CONTRIBUTOR

Hunain Tahir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring