Php 无法从继承方法中的子类访问私有变量

Php 无法从继承方法中的子类访问私有变量,php,Php,此代码给我错误无法访问私有属性C:$abc 在父类中使用私有变量时,这一点很明显,但在该代码中,私有变量位于子类中,属性_存在可以看到该变量。我在php文档中找不到解释 我的困惑如下。 父方法在子方法中继承。我的假设是,这个方法应该可以访问child中的变量,但它没有property\u存在知道此属性,但无法设置它。使用受保护$abc`可见性原因是您在同一类中使用父方法(configure()),因此父类中的abc变量不能是私有的访问原因 class Configurable { pro

此代码给我错误
无法访问私有属性C:$abc

父类
中使用私有变量时,这一点很明显,但在该代码中,私有变量位于子类中,
属性_存在
可以看到该变量。我在php文档中找不到解释

我的困惑如下。
父方法在子方法中继承。我的假设是,这个方法应该可以访问child中的变量,但它没有
property\u存在
知道此属性,但无法设置它。

使用
受保护
$abc`可见性原因是您在同一类中使用父方法(configure()),因此父类中的abc变量不能是私有的访问原因

class Configurable
{
    protected function configure(array $config): void
    {
        foreach ($config as $key => $value){
             if (property_exists($this, $key)){
                $this->{$key} = $value;
            }
        }
    }
}

class C extends Configurable
{
    private $abc;

    public function __construct()
    {
        $this->configure(['abc' => 5]);
    }
}

$c = new C();
如果您想使用Private来定义变量,那么您应该在同一个类中定义configure()方法。而\uu get方法用于当您试图访问受保护的私有变量时,将调用此u get()函数

class Configurable
{
    protected function configure(array $config): void
    {
        foreach ($config as $key => $value){
             if (property_exists($this, $key)){
                $this->{$key} = $value;
            }
        }
    }
}

class C extends Configurable
{
    protected $abc;

    public function __construct()
    {
        $this->configure(['abc' => 5]);
    }

    //this method is when you're trying to access $c->abc that'll return from here.
    public function __get($method)
    {
        return $this->$method;
    }
}

$c = new C();
echo $c->abc;

您的第二个示例违背了继承的目的,并且与SOLID相矛盾。我建议@vitaley不要采用它。他应该只使用
protected
而不是
private
。同意@Aydin4ik,但他试图使用private访问变量,这就是为什么我只为他使用第二种方法。
class Configurable
{
    protected function configure(array $config): void
    {
        foreach ($config as $key => $value){
             if (property_exists($this, $key)){
                $this->{$key} = $value;
            }
        }
    }
}

class C extends Configurable
{
    private $abc;

    public function __construct()
    {
        $this->configure(['abc' => 5]);
    }

    //method overriding
    protected function configure(array $config): void
    {
        foreach ($config as $key => $value){
             if (property_exists($this, $key)){
                $this->{$key} = $value;
            }
        }
    }

    public function __get($method)
    {
        return $this->$method;
    }
}

$c = new C();

echo $c->abc;