这种行为是完全正常的。事实上,如果您的属性是对象(始终通过引用传递),您甚至不需要显式创建引用:
class Foo
{
private Datetime $when;
public function __construct()
{
$this->when = new DateTime('1950-12-31');
}
public function getWhen(): DateTime
{
return $this->when;
}
}
$f = new Foo();
$w = $f->getWhen();
$w->modify('+50 years');
var_dump($w, $f);
object(DateTime)#2 (3) {
["date"]=>
string(26) "2000-12-31 00:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/Madrid"
}
object(Foo)#1 (1) {
["when":"Foo":private]=>
object(DateTime)#2 (3) {
["date"]=>
string(26) "2000-12-31 00:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/Madrid"
}
}
这与您引用的文档并不矛盾。该属性本身无法访问:
$f->when;
// PHP Fatal error: Uncaught Error: Cannot access private property Foo::$when
参考文献是一种不同的语言功能。也许通过另一个例子更容易理解:
function a(){
$local_variable = 1;
b($local_variable);
echo "b modified a's local variable: $local_variable\n";
}
function b(&$number)
{
echo "b can read a's local variable: $number\n";
$number++;
}
a();
b can read a's local variable: 1
b modified a's local variable: 2
翻阅古今