本文介绍了基类不允许访问私有成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以发誓,在标准 OOP 中,您可以从基类中的方法访问具体类的私有成员.PHP 只是以不同的方式实现这一点,还是我做错了什么,或者我的理解完全错误?

I could have sworn that in standard OOP, you can access the private members of the concrete class from a method in the base class. Does PHP just implement this differently, or am I doing something wrong, or was my understanding entirely wrong?

<?php

class Base {
  public function __toString() {
    return $this->name;
  }
}

class Concrete extends Base {
  private $name;

  public function __construct($name) {
    $this->name = $name;
  }
}

$o = new Concrete('foobar');
echo $o;

上面的代码片段抛出致命错误:无法访问第 5 行的私有属性 Concrete::$name.如果我将 $name 的访问级别更改为 protected,它会起作用.

The above code fragment throws Fatal error: Cannot access private property Concrete::$name on line 5. It works if I change the access level of $name to protected.

演示

推荐答案

private 通常意味着它只能从类内部访问.我认为这是预期的行为.

private usually means that it can be accessed ONLY from within the class. I think this is expected behaviour.

来自 PHP 文档:

属性或方法的可见性可以通过在声明前加上关键字 public、protected 或 private 来定义.声明为 public 的类成员可以在任何地方访问.声明为 protected 的成员只能在类本身内以及被继承类和父类访问.声明为私有的成员只能由定义该成员的类访问.

这篇关于基类不允许访问私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 08:03
查看更多