PHP 函数 `get_object_vars` 没有从继承的方法中获取私有(private)变量

标签 php

在这个例子中,我假设从 data 调用的函数 getVars 将能够返回 B 的私有(private)变量名称,因为 $thisB 的实例。

取而代之的是,$this->getVars() 返回一个空数组。

  • 调用get_object_vars 私有(private)变量不是可见的吗?
  • getVars 不是继承给 B 的方法,并且像在其中声明一样调用吗?
  • 如何从声明的方法中获取私有(private)变量名 一个抽象类?

例子:

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)属性仅可用于该类的方法。尝试使用 protected 属性来确保继承的方法可以访问它们。

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited classes. Members declared as private may only be accessed by the class that defines the member.

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

关于PHP 函数 `get_object_vars` 没有从继承的方法中获取私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38055045/

相关文章:

php - 函数开始时出现解析错误 : syntax error, 意外的 T_VARIABLE

php - 防止 UIButtons 操作运行多次

php - 找不到 Magento 列 : 1054 Unknown column 'cat_index_position' in 'order clause'

php - 测试 Twig 中的变量相等性

php - 更新时插入。复合键

php - SSL/cUrl/PHP 请求在 Zend 服务器中失败

php - 如何自定义 Zend_Tool 输出?

php - 用户提供的输入 SQL 转义

php - 来自另一个用户的 DBus

php - 启动 WAMP 后,mysqld.exe 立即使用大量内存(450 MB)