How to make a variable private to a trait?

后端 未结 4 663
广开言路
广开言路 2021-02-05 13:17

I\'d like to reuse a functionality several times in a single class. This functionality relies on a private variable:

tr         


        
4条回答
  •  广开言路
    2021-02-05 13:51

    Declaring a trait with use will not create an instance of that trait. Traits are basically just code that is copy and pasted into the using class. The as will only create an Alias for that method, e.g. it will add something like

    public function getHomeAddress()
    {
        return $this->getAddress();
    }
    

    to your User class. But it will still only be that one trait. There will not be two different $address properties, but just one.

    You could make the methods private and then delegate any public calls to it via __call by switch/casing on the method name and using an array for address, e.g.

    trait Address {
        private $address = array();
    
        private function getAddress($type) {
            return $this->address[$type];
        }
    
        private function setAddress($type, $address) {
            $this->address[$type] = $address;
        }
    
        public function __call($method, $args) {
            switch ($method) {
                case 'setHomeAddress':
                    return $this->setAddress('home', $args[0]);
                // more cases …
            }
        }
    }
    

    But that is just a can of worms.

    In other words, you cannot sanely do what you are trying to do with traits. Either use two different traits. Or use good old aggregation and add concrete proxy methods.

提交回复
热议问题