gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:26:40 25 4
gpt4 key购买 nike

在这个例子中,我假设从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com