PHP:改变变量范围


PHP: Change variable scope

是否可以在另一个类中将变量的访问权限从public更改为protected ?在我看来,根据我的一点点知识,这是不可能的,但我希望PHP专家可以帮助我找出这是真的吗?

class A
{
    var $myvar;
}
Class B
{
    function __Construct()
    {
        $A = new A();
        // Can I change scope of $A->myvar to protected?
    }
}

可能不是最好的方法,但它会满足您的需要:

class A
{
    protected $myvar;
    protected $isMyVarPublic;
    function __construct($isMyVarPublic = true)
    {
        $this->isMyVarPublic = $isMyVarPublic;
    }
    function getMyVar()
    {
        if (!$this->isMyVarPublic) {
            throw new Exception("myvar variable is not gettable");
        }
        return $this->myvar;
    }
    function setMyVar($val)
    {
        if (!$this->isMyVarPublic) {
            throw new Exception("myvar variable is not settable");
        }
        $this->myvar = $val;
    }
}
class B
{
    function __construct()
    {
        $A = new A(false);
    }
}