我是一名中級C++程序員,知道您可以傳遞一個常量引用作爲參數,以防止編輯爲實際變量。我想知道如果我可以在PHP中做到這一點?PHP常量參考
Q
PHP常量參考
2
A
回答
5
1
這是你在說什麼:
<?php
$a = 10;
function foo($p_a) {
// passing by value is the default
$p_a++;
}
foo($a);
echo $a; // prints 10
$a = 10;
function bar(&$p_a) {
//-------^ passing by reference
$p_a++;
}
bar($a);
echo $a; // prints 11
?>
0
@Salman A,即只對標工作,當他們被引用或沒有通過行爲的對象不同。看起來這兩種方法之間沒有真正的區別!
<?php
class X
{
static $instances = 0;
public $instance;
public $str;
function __construct($str)
{
$this->instance = ++self::$instances;
$this->str = $str;
}
public function __toString()
{
return "instance: ".$this->instance." str: ".$this->str;
}
}
class Y extends X
{
public function __toString()
{
return "Y:".parent::__toString();
}
}
// Pass NORMAL
function modify_1($o)
{
$o->str = __FUNCTION__;
}
// Pass BY-REFERENCE
function modify_2(&$o)
{
$o->str = __FUNCTION__;
}
// Pass NORMAL - Obj Replace
function modify_3($o)
{
$o = new Y(__FUNCTION__);
}
// Pass BY-REFERENCE - Obj Replace
function modify_4(&$o)
{
$o = new Y(__FUNCTION__);
}
$x = new X('main');
echo "$x\n";
modify_1($x);
echo "$x\n";
modify_2($x);
echo "$x\n";
modify_3($x);
echo "$x\n";
modify_4($x);
echo "$x\n";
生成下面的輸出;
instance: 1 str: main
instance: 1 str: modify_1
instance: 1 str: modify_2
instance: 1 str: modify_2
Y:instance: 3 str: modify_4
我期待
instance: 1 str: main
instance: 1 str: main
instance: 1 str: modify_2
instance: 1 str: modify_2
Y:instance: 3 str: modify_4
所以我的結論是;如果我們正在處理對象(本身)或標量,它似乎工作;但不是對象的屬性或方法。
相關問題
- 1. MIDL(常量)參考文獻
- 2. PHP中的參考變量
- 3. 修改常量參數參考
- 4. 模板函數和常量/非常量參考參數
- 5. Kotlin - 常量的未解決的參考
- 6. 常量性參考類成員
- 7. C++常量在參考上丟失
- 8. 常量指針返回參考
- 9. 使用參考修改常量對象
- 10. iPhone - NSError參考:常量和代碼
- 11. 參考在PHP
- 12. null參考異常
- 13. Jquery參考中的PHP變量
- 14. PHP:製作參考變量的副本
- 15. C++參考本地變量與參考
- 16. 參考變量和常量指針變量有什麼區別?
- 17. 返回參考PHP
- 18. 問題PHP參考
- 19. php傳遞參考
- 20. php參考傳遞
- 21. PHP返回參考
- 22. 矢量::在參考
- 23. 參考變量AS3
- 24. Java - 參考變量
- 25. Moq'ing參考變量
- 26. C++參考變量
- 27. 傳輸參數爲const參考與正常參考
- 28. 錯誤推回參考常量向量的元素
- 29. 異常:STATUS_ACCESS_VIOLATION - 指針參考
- 30. 作爲方法參數的常量PHP
你的標題很混亂,因爲PHP有類常量。 – 2011-01-22 06:46:09
標題看起來不錯,但是因爲我沒有找到任何等價物,所以此答案建議克隆該對象,然後將其傳遞給一個函數 - http://stackoverflow.com/a/11368155/1835470,但克隆使得只是一個淺拷貝... http://php.net/manual/en/language.oop5.cloning.php – 2015-04-15 20:22:57