简体   繁体   English

PHP函数`get_object_vars`不会从继承的方法中获取私有变量

[英]PHP function `get_object_vars` doesn't get private vars from inherited method

In this example I supposed that function getVars called from data would be able to return private vars names of B due to $this is an instance of B . 在此示例中,我认为从data调用的函数getVars将能够返回B私有变量名称,原因是$thisB的实例。

Instead of it, $this->getVars() returns an empty array. 取而代之的是$this->getVars()返回一个空数组。

  • Isn't get_object_vars called been private variables visible? 调用get_object_vars是否可以看到私有变量?
  • Isn't getVars a method inherited to B and called as if it was declared in it? getVars是否不是继承给B并像在其中声明的那样调用的方法?
  • How can I get private variable names from a method declared in an abstract class? 如何从抽象类中声明的方法获取私有变量名称?

Example: 例:

abstract class A
{
    public function getVars()
    {
        return get_object_vars($this);
    }
}

class B extends A
{
    private $a;
    private $b;
    private $c;

    public function data()
    {
        ...

        foreach($this->getVars() as $var) {
            ...
        }
    }
}

Private properties are only available to that class's methods. 私有属性仅可用于该类的方法。 Try using protected properties to ensure the inherited methods have access to them. 尝试使用受保护的属性,以确保继承的方法可以访问它们。

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. 属性或方法的可见性可以通过在声明的前面加上关键字public,protected或private来定义。 Class members declared public can be accessed everywhere. 宣告为公开的班级成员可以在任何地方访问。 Members declared protected can be accessed only within the class itself and by inherited classes. 声明为protected的成员只能在类本身内以及被继承的类访问。 Members declared as private may only be accessed by the class that defines the member. 声明为私有的成员只能由定义该成员的类访问。

http://php.net/manual/en/language.oop5.visibility.php http://php.net/manual/en/language.oop5.visibility.php

Yes because get_object_vars is scope sensitive. 是的,因为get_object_vars是作用域敏感的。 If you don't wish to change the visibility of the variables then call get_object_vars directly from function data() . 如果您不想更改变量的可见性,请直接从函数data()调用get_object_vars

If you want to keep the code inheritance as it is, you'll have to change the visibility of the variables to protected. 如果要保持代码继承不变,则必须将变量的可见性更改为protected。

abstract class A
{
    public function getVars()
    {
        return get_object_vars($this);
    }
}

class B extends A
{
    protected $a;
    protected $b;
    protected $c;

    public function data()
    {
        return $this->getVars();
    }
}

$a = new B();
print_r($a->data());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM