在下面的示例中,我收到一条错误,指出 $foo->_test
的值无法访问,因为它是私有(private)的。我做错了什么?
<?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';
}
}
?>
感谢任何帮助。
最佳答案
私有(private)变量仅对声明它们的直接类可见。您正在寻找的是protected
,如果没有这个,您实际上就是在对象中创建两个不同的成员变量。
class Foo
{
protected $_test = array();
}
class Bar extends Foo
{
public function test()
{
$this->_test = 'opa';
}
}
[编辑]
您还尝试完全访问类外部的私有(private)(即将受到保护)成员变量。这将始终被禁止。除非在这种情况下,否则您将创建第二个 public
成员变量,这就是没有显示错误的原因。您没有提到您希望看到错误,所以我假设这是您的问题。
[编辑]
这是 var 转储:
object(Bar)#1 (2) {
["_test:private"]=>
array(0) {
}
["_test"]=>
string(3) "opa"
}
[编辑]
我在编写的框架中所做的一件事是创建一个几乎可以在任何地方扩展的基类。该类所做的一件事是使用 __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 );
关于php - private var 在 php 类中无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8455086/