private var在类php中没有按预期工作

use*_*478 2 php var private class

在下面的示例中,我收到一个错误,指出$foo->_test由于它是私有的,因此无法访问该值.我究竟做错了什么?

<?php
$foo = new Bar;
$foo->test();
print_r( $foo->_test );

class Foo
{
    private $_test = array();
}


class Bar extends Foo
{
    public function test()
    {
        $this->_test = 'opa';
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏.

Tim*_*m G 5

私有变量仅对声明它们的直接类可见.你正在寻找的是protected 没有这个你有效地在你的对象中创建两个不同的成员变量.

class Foo
{
    protected $_test = array();
}

class Bar extends Foo
{
    public function test()
    {
        $this->_test = 'opa';
    }
}
Run Code Online (Sandbox Code Playgroud)

[edit]您还试图完全访问类外的私有(即将受到保护的)成员变量.这将永远不被允许.除非在这种情况下,您正在创建第二个public成员变量,这就是显示没有错误的原因.你没有提到你期望看到错误,所以我假设这是一个你有的问题.

[编辑]

这是var转储:

object(Bar)#1 (2) {
  ["_test:private"]=>
  array(0) {
  }
  ["_test"]=>
  string(3) "opa"
}
Run Code Online (Sandbox Code Playgroud)

[编辑]

我在我编写的框架中做的一件事是创建一个几乎无处不在的基类.这个类所做的一件事是使用__get__set方法来强制声明类成员变量 - 它有助于缩小代码问题,例如你所拥有的代码问题.

<?

abstract class tgsfBase
{
    public function __get( $name )
    {
        throw new Exception( 'Undefined class member "' . $name . "\"\nYou must declare all variables you'll be using in the class definition." );
    }
    //------------------------------------------------------------------------
    public function __set( $name, $value )
    {
        throw new Exception( 'SET: Undeclared class variable ' . $name . "\nYou must declare all variables you'll be using in the class definition." );
    }

}

class Foo extends tgsfBase
{
    private $_test = array();
}

class Bar extends Foo
{
    public function test()
    {
        $this->_test = 'opa';
    }
}

header( 'content-type:text/plain');

$foo = new Bar;
$foo->test();
var_dump( $foo );
print_r( $foo->_test );
Run Code Online (Sandbox Code Playgroud)