php中访问修饰符的知识点总结

为什么需要访问权限?

防止覆盖变量名称和函数名称

我们下来看一下public的使用,public是可以从任何地方访问的最广泛的访问限定符。

假设A先生开发overlapFuncBase,B先生继承overlapFuncBase创建了overlapFunc的例子。

<?php
class overlapFuncBase {
  public $s = 1;
}
class overlapFunc extends overlapFuncBase { 
  public $s = 2;
}
$obj_overlap = new overlapFunc();
var_dump($obj_overlap);

结果

object(overlapFunc)#1 (1) {
  ["s":"overlapFunc":public] => int(2)
}

在B overlapFunc中,我可以使用由A先生创建的overlapFuncBase,但由于变量名$ s是相同的,覆盖了它。

所以这时就需要访问修饰符。

<?php
class overlapFuncBase {
  private $s = 1;
}
class overlapFunc extends overlapFuncBase { 
  private $s = 2;
}
$obj_overlap = new overlapFunc();
var_dump($obj_overlap)

结果

object(overlapFunc)#1 (2) {
  ["s":"overlapFunc":private] => int(2)
  ["s":"overlapFuncBase":private] => int(1)
}

与第一个代码的不同之处在于我们在变量$ s之前将访问修饰符public更改为private。

private表示你只能在自己的类中访问。

因此,即使是A创建的每个类都有相同变量名,现在也可以获得不同的结果。

访问修饰符的类型

访问修饰符有private、protected和public

对应范围按以下顺序增加

private → protected → public

还有另一个名为static的特殊访问修饰符,如果你指定了类名,你可以在任何地方使用它。