获取子(继承)类的对象属性 - 不包括基类属性


Get Object properties for sub(inherited) class - Excluding Base class properties

我正在使用PHP和函数get_object_vars()

我有两个班级

class A
{
    var $color = 'blue';
    var $wood = 'oak';
}
class B extends A
{
}

如果我们运行以下代码

$B = new B();
$B->website = 'stackoverflow';
var_dump(get_object_vars($B));

输出为

array(3) {
["color"]=>
string(4) "blue"
["wood"]=>
string(3) "oak"
["website"]=>
string(13) "stackoverflow"
}

我理想的输出是

array(1) {
["website"]=>
string(13) "stackoverflow"
}

这可能吗?

根据 PHP get_object_vars 文档:"根据作用域获取给定对象的可访问非静态属性"。

在代码中,get_object_vars 函数是从对象范围之外调用的,因此,您将看到公共属性。

如果作用域是对象本身(从类实例内部调用),则私有、受保护或私有属性是可见的。(静态属性除外)

因此,如果您需要继承 B 类中的继承$color和$wood,则可以将它们声明为受保护。如果不想继承,请将这两个变量声明为私有变量

例:

class A
{
    protected $color = 'blue';
    protected $wood = 'oak';
}
class B extends A{
    public function __construct(){
        echo "SCOPE: Self object: ";
        var_dump("Color in B: " . $this->color);
        var_dump("Wood in B: " . $this->wood);
    }
    public function get_my_vars(){
        echo "SCOPE: Self object: ";
        echo "My vars";
        var_dump(get_object_vars($this));
    }
}
$B = new B();
$B->website = 'stackoverflow';
echo "SCOPE: Outside object: B vars";
var_dump(get_object_vars($B));
$B->get_my_vars();
===============
Output:
SCOPE: Self object:
string 'Color in B: blue' (length=16)
string 'Wood in B: oak' (length=14)
SCOPE: Outside object: B vars
array (size=1)
  'website' => string 'stackoverflow' (length=13)
SCOPE: Self object: My vars
array (size=3)
  'color' => string 'blue' (length=4)
  'wood' => string 'oak' (length=3)
  'website' => string 'stackoverflow' (length=13)