I'm a intermediate C++ programmer and know that you can pass a constant reference as a parameter in order to prevent editing to the actual variable. I was wondering if I could do this in PHP?
No, there is no equivalent to C++'s const
qualifier in PHP.
Is this what you're talking about:
<?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
?>
@Salman A, that works only for scalar, the behaviour is different for objects when they are passed by reference or not. It looks like there is no real difference between the two methods!
<?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
";
modify_1($x);
echo "$x
";
modify_2($x);
echo "$x
";
modify_3($x);
echo "$x
";
modify_4($x);
echo "$x
";
That generated the below output;
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
I was expecting
instance: 1 str: main
instance: 1 str: main
instance: 1 str: modify_2
instance: 1 str: modify_2
Y:instance: 3 str: modify_4
So my conclusion is; it does seem to work if we are dealing with object ( itself ) or a scalar; but not an object's property or its method.