How to make a variable private to a trait?

后端 未结 4 662
广开言路
广开言路 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:48

    Some years down the line, I followed up on a comment in bug 63629 and produced the following:

    addresses[substr($calledAs, 3)];
        }
    
        public function setAddress($address) {
            $calledAs = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0]['function'];
            $this->addresses[substr($calledAs, 3)] = $address;
        }
    }
    class TestClass
    {
        use TestTrait { getAddress as getHomeAddress; setAddress as setHomeAddress; }
        use TestTrait { getAddress as getWorkAddress; setAddress as setWorkAddress; }
    }
    $c = new TestClass();
    
    $c->setHomeAddress("High Street, Luton");
    echo $c->getHomeAddress();
    echo "\n";
    $c->setWorkAddress("Business Name, London");
    echo $c->getWorkAddress();
    echo "\n";
    

    which outputs

    High Street, Luton
    Business Name, London
    

    It can be done! (With thanks to Dave Farrell whose answer inspired this one.) The arguments to debug_backtrace are an attempt to minimize memory usage, I'm not certain how much of an effect on performance that is.

提交回复
热议问题