在这个例子中,我假设从 data
调用的函数 getVars
将能够返回 B
的私有(private)变量名称,因为 $this
是 B
的实例。
取而代之的是,$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.
关于PHP 函数 `get_object_vars` 没有从继承的方法中获取私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38055045/