0

変数のアクセスを public から別のクラスの保護に変更することは可能ですか? 私の意見では、これは私のわずかな知識では不可能ですが、PHP の専門家が私を助けてくれることを願っています。

class A
{
    var $myvar;
}

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

1 に答える 1

1

おそらく最善の方法ではありませんが、必要なことは実行できます。

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);
    }
}
于 2013-04-27T03:21:21.210 に答える