那麼,您的示例代碼不是PHP,但是,如果您返回對受保護變量的引用,則可以使用該引用修改類的作用域之外的數據。下面是一個例子:
<?php
class foo {
protected $bar;
public function __construct()
{
$this->bar = array();
}
public function &getBar()
{
return $this->bar;
}
}
class foo2 {
var $barReference;
var $fooInstance;
public function __construct()
{
$this->fooInstance = new foo();
$this->barReference = &$this->fooInstance->getBar();
}
}
$testObj = new foo2();
$testObj->barReference[] = 'apple';
$testObj->barReference[] = 'peanut';
?>
<h1>Reference</h1>
<pre><?php print_r($testObj->barReference) ?></pre>
<h1>Object</h1>
<pre><?php print_r($testObj->fooInstance) ?></pre>
當執行該代碼時,print_r()
結果將顯示,存儲在$testObj->fooInstance
數據已被使用存儲在$testObj->barReference
參考修改。但是,問題在於函數必須定義爲按引用返回,並且調用還必須請求引用。你需要他們兩個!下面是相關頁面出來的PHP手冊:
http://www.php.net/manual/en/language.references.return.php
我不禁想知道爲什麼你這樣做,或者如果它甚至是一個好主意...... – 2008-09-16 05:59:47
原諒我,但使用一個公共變量,並且無需「破解」訪問受保護的變量?你在做什麼似乎是一個相當糟糕的主意......也許如果你告訴了我們更多你想要完成的事情,我們可以找到一個好方法去實現它... – 2008-09-16 06:03:43