Menu Home

PHP: trait & Resolve Conflict

        <?php

        trait Logger {

            public function log($logString) {
                $className = __CLASS__;
                echo date("Y-m-d:h:i:s", time()) . ": [{$className}] {$logString} <br />";
            }

        }

        class User {

            use Logger;

            function __construct($name = '') {
                $this->name = $name;
                $this->log("Create user '{$this->name}'");
            }

            function __toString() {
                return $this->name;
            }

        }

        Class UserGroup {

            use Logger;

            private $users = array();

            public function addUser(User $user) {
                if(!$this->includesUser($user)) {
                    $this->users[] = $user;
                    $this->log("Added user '{$user}' to group");
                }
            }

            private function includesUser(User $user) {
                return array_search($user, $this->users, true);
            }
            
            public function showAll() {
                foreach($this->users as $name) {
                    echo "{$name} <br />";
                }
            }
        }
        
        $group = new UserGroup;
        $group->addUser(new User("lnmcc"));
        $group->addUser(new User("wangsijie"));
        $group->showAll();
        ?>

output:

2014-11-29:04:49:23: [User] Create user 'lnmcc' 
2014-11-29:04:49:23: [UserGroup] Added user 'lnmcc' to group 
2014-11-29:04:49:23: [User] Create user 'wangsijie' 
2014-11-29:04:49:23: [UserGroup] Added user 'wangsijie' to group 
lnmcc 
wangsijie

Resolve Conflicts

Use the as keyword to alias a trait’s method name.

        <?php
        trait Command1 {
            function run() {
                echo "executing command1 ... <br />";
            }
        }
        
        trait Command2 {
            function run() {
                echo "executing command2 ... <br />";
            }
        }
        
        class TestCommand {
            use Command1, Command2 {
                Command1::run as Command1Run;
                Command2::run insteadof Command1;
            }
        }
        
        $test = new TestCommand();
        $test->run();
        $test->Command1Run();
        ?>

output:

executing command2 ... 
executing command1 ... 

Categories: php

Tagged as:

lnmcc

Leave a Reply

Your email address will not be published.