2011-01-22 91 views
2

我是一名中級C++程序員,知道您可以傳遞一個常量引用作爲參數,以防止編輯爲實際變量。我想知道如果我可以在PHP中做到這一點?PHP常量參考

+0

你的標題很混亂,因爲PHP有​​類常量。 – 2011-01-22 06:46:09

+0

標題看起來不錯,但是因爲我沒有找到任何等價物,所以此答案建議克隆該對象,然後將其傳遞給一個函數 - http://stackoverflow.com/a/11368155/1835470,但克隆使得只是一個淺拷貝... http://php.net/manual/en/language.oop5.cloning.php – 2015-04-15 20:22:57

回答

5

不,在PHP中沒有等同於C++的const限定符。

+0

如果他來自C++(你不能將對象設置爲const),他不會試圖去做。 – ehudokai 2011-01-22 04:09:33

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 

所以我的結論是;如果我們正在處理對象(本身)或標量,它似乎工作;但不是對象的屬性或方法。