如何使变量对特征具有私有性? [英] How to make a variable private to a trait?

查看:70
本文介绍了如何使变量对特征具有私有性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个类中多次重用功能.此功能依赖于私有变量:

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

trait Address {
    private $address;

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

    public function setAddress($address) {
        $this->address = $address;
    }
}

我发现使用的唯一方法特质两次,如下:

class User  {
    use Address {
        getAddress as getHomeAddress;
        setAddress as setHomeAddress;

        getAddress as getWorkAddress;            
        setAddress as setWorkAddress;
    }
}

问题在于,这样做,私有变量$address在不同的方法之间共享,并且代码无法按预期工作:

The problem is, by doing this, the private variable $address is shared across the different methods, and the code will not work as expected:

$user = new User();
$user->setHomeAddress('21 Jump Street');
echo $user->getWorkAddress(); // 21 Jump Street

是否存在一种解决方案,可以在不共享其私有变量的情况下真正使用两次特征?

Is there a solution to really use the trait twice, while not sharing its private variables?

推荐答案

使用use声明特征将不会创建该特征的实例.特性基本上只是复制并粘贴到using类中的代码. as只会为该方法创建一个别名,例如它将添加类似

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();
}

到您的User类.但这仍然只是那一个特质.不会有两个不同的$address属性,而只有一个.

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 …
        }
    }
}

但这只是一罐蠕虫.

换句话说,您无法理智地完成要使用特质的工作.可以使用两个不同的特征.或使用良好的旧聚合并添加具体的代理方法.

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.

这篇关于如何使变量对特征具有私有性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆