是否可以在另一个类中将变量的访问权限从公共更改为受保护。 在我看来,根据我的小知识,这是不可能的,但我希望有PHP专家可以帮助我找出是真的吗?
class A
{
var $myvar;
}
Class B
{
function __Construct()
{
$A = new A();
// Can I change scope of $A->myvar to protected?
}
}
答案 0 :(得分: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);
}
}