我是一名中級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. Kotlin - 常量的未解決的參考
- 5. iPhone - NSError參考:常量和代碼
- 6. 使用參考修改常量對象
- 7. 常量指針返回參考
- 8. C++常量在參考上丟失
- 9. null參考異常
- 10. PHP:製作參考變量的副本
- 11. Jquery參考中的PHP變量
- 12. C++參考本地變量與參考
- 13. 參考變量和常量指針變量有什麼區別?
- 14. 問題PHP參考
- 15. php參考傳遞
- 16. PHP返回參考
- 17. 參考變量AS3
- 18. 矢量::在參考
- 19. Moq'ing參考變量
- 20. 異常:STATUS_ACCESS_VIOLATION - 指針參考
- 21. PHP常量字符串參數標記
- 22. php通過參考差異
- 23. PHP OOP關於參考
- 24. PHP參考資料:瞭解
- 25. PHP參考和指針
- 26. C#Web參考和PHP
- 27. PHP參考靜態方法
- 28. php參考值與值
- 29. PHP Oracle參考光標
- 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