1 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超13個(gè)贊
這種行為是完全正常的。事實(shí)上,如果您的屬性是對(duì)象(始終通過引用傳遞),您甚至不需要顯式創(chuàng)建引用:
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
參考文獻(xiàn)是一種不同的語言功能。也許通過另一個(gè)例子更容易理解:
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
- 1 回答
- 0 關(guān)注
- 115 瀏覽
添加回答
舉報(bào)