是否可以将变量的访问权限从公共更改为另一个类中的受保护。在我看来,根据我的小知识这是不可能的,但我希望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);
}
}