[英]turning variable into class variable
在我的PHP課上,
public $a;
public $b;
public $c;
public $d;
我在構造中設置了值。
我現在正嘗試編寫一個更新函數,並且試圖檢查它們是否正在更新,例如$ a,保持不變。
function update($what, $to) {
if ($to == $this->what) return false;
...
}
$updated = $instance->update($a, "Foobar");
if ($updated) echo "Updated";
else echo "You didn't change the value";
但是因為我知道這條線
if ($to == $this->what) return false;
是無效的,我正在尋找一種新的編寫方式。
有想法嗎?
提前致謝
解決難題的方法是變量變量。 您的更新功能必須按以下方式分配它:
$this->{$what} = $to;
if-check將相應地:
if ($to == $this->{$what}) return false;
而且,您實際上不能使用變量$a
調用update()方法。 您必須給它一個變量名作為字符串:
$instance->update("a", "Foobar");
您可以執行以下操作:
if ($to == $this->$what) return false;
並這樣稱呼它:
update("a", "Foobar");
這使用了變量變量( http://php.net/manual/zh/language.variables.variable.php )。
您也可以通過引用傳遞:
function update(&$what, $to) {
if ($to == $what) return false;
...
}
並像在示例中一樣進行調用。
$this->$what
應該可以解決問題,如果$what = 'a'
您通常希望避免這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.