访问类外的受保护成员变量

14 php variables class protected member

我通过访问有人已经到位,一类函数查询的字段的ID.结果是返回带有受保护成员变量的对象.我很难看到如何访问类外的成员变量值.

Paw*_*wka 19

从公共访问受保护或私有变量是不正确的(这就是为什么它们受到保护或私有).所以更好的是扩展类和访问所需的属性或使getter方法公开.但是如果你仍然希望获得没有扩展的属性,并且如果你使用PHP 5,你可以使用Reflection类访问.实际上尝试ReflectionProperty类.

class Foo { protected $bar; }
$foo = new Foo();

$rp = new ReflectionProperty('Foo', 'bar');
$rp->setAccessible(true);
echo $rp->getValue($foo);
Run Code Online (Sandbox Code Playgroud)

  • +1`ReflectionProperty`对我有用。但是不要忘了调用`ReflectionProperty :: setAccessible(true)`。 (2认同)

Kas*_*ncz 14

这是正确的答案:

我们可以使用Closure类的bind()或bindTo方法来访问某些类的私有/受保护数据,例如:

class MyClass {
          protected $variable = 'I am protected variable!';
}

$closure = function() {
          return $this->variable;
};

$result = Closure::bind($closure, new MyClass(), 'MyClass');
echo $result(); // I am protected variable!
Run Code Online (Sandbox Code Playgroud)

  • 哇!那好美丽.为什么这不会有更多的选票? (4认同)

小智 13

只需在课程中添加"get"方法即可.

class Foo
{
    protected $bar = 'Hello World!';

    public function getBar()
    {
        return $this->bar;
    }
}

$baz = new Foo();

echo $baz->getBar();
Run Code Online (Sandbox Code Playgroud)