0

I'm trying to run two functions from two separate traits which would be applied within one class but sequentially one adding onto the other. A simple example is shown below

trait UserLevel{
    public function get(){
        echo 'World';
    }
}

trait SpecialUser{
    use UserLevel {
        UserLevel::get as userGet;
    }

     public function get(){

         echo 'Hello ';
         $this->userGet();
     }
}

Class GetUser{
    use UserLevel, SpecialUser;
}

$user = new GetUser;
$user->get(); 

All my googling on this issue just show how to use insteadofto overwrite one with the other.

Edit:

This question isnt a duplicate of the referenced one. On running of the code with the prescribed changes I get

Fatal error: Trait method get has not been applied, because there are collisions with other trait methods on GetUser in /in/hg9ok on line 20

Process exited with code 255.

Thanks

Stanley Ngumo
  • 4,089
  • 8
  • 44
  • 64
  • Possible duplicate of [How to override trait function and call it from the overridden function?](https://stackoverflow.com/questions/11939166/how-to-override-trait-function-and-call-it-from-the-overridden-function) – Nigel Ren Jun 07 '18 at 12:42
  • Not entirely sure about the duplicate, but it may point you in the direction of how to get access to both methods. – Nigel Ren Jun 07 '18 at 12:44
  • You should start by reading the manual: http://php.net/manual/en/language.oop5.traits.php. There is no `()` after the trait name. The code you posted [does not compile](https://3v4l.org/bk3ae) because of those parentheses. – axiac Jun 07 '18 at 12:44

1 Answers1

0

Fundamentally no you can't achieve what you're describing. The technical reason is you'll get a fatal error if you try to use more than one trait with the same method names (see the "Conflict resolution" part of the documentation) and you can't selectively access a method from within a trait (i.e. UserLevel::get) but really this is either a misunderstanding or a misuse of traits.

Traits are there for horizontal composition of functionality and the key part of your example which indicates this isn't the case is the "SpecialUser" trait. If this is indeed a special user, then why isn't it a sub class of "User" with the functionality you describe rather than a trait?

It's a question of what you're trying to achieve here - not from a code point of view but more holistically - and applying OOP to that, rather than, what seems to be happening here which is the other way around.

John Noel
  • 1,401
  • 10
  • 13