2013-04-27 101 views
0

是否可以将变量的访问权限从public更改为另一个类中的protected。 在我看来,根据我的小知识,这是不可能的,但我希望有人在PHP的专家可以帮助我发现是真的吗?PHP:更改变量范围

class A 
{ 
    var $myvar; 
} 

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

回答

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); 
    } 
} 
+0

太谢谢你了!是否可以直接从'B类'改变范围?我想隐藏'A类'的所有更改。 – 2013-04-27 03:26:59

+0

不是我知道的,没有扩展课程。 “隐藏A级的所有更改”是什么意思? – 2013-04-27 03:31:20

+0

我的意思是说,我需要隐藏大部分关于A类变量的过程。相反,我在B类中完成了我的工作,并给出了使用A类最后一个结果的人。谢谢,我终于接受这是不可能的要求。 – 2013-04-27 08:18:20