Thursday, June 4, 2009

passing parameters to function: PHP4 and PHP5

Variables

In PHP4 and PHP5, variables by default are passed by value (copy) to functions. It means that outside the function the variables don't change

$v = 1;
function
increment($v) { $v++; }
increment($v);
print
$v; // 1 !!

If you want to pass by reference, use the operator &
$v = 1;
function
increment(&$v) { $v++; }
increment($v);
print
$v; // 2 !!

Objects

by default:
  • PHP4: object passed by value
    inside the function, the passed object are cloned !
  • PHP5: object passed by reference
    equivalent explanation: the reference of the object is passed by value
class A{ public $val;}
function
incrementA($a){$a->val++; }
$a = new A(); $a->val = 1;
print
$a->val; // PHP4 and PHP print "1"
incrementA($a);
print
$a->val; // PHP4 prints "1", PHP5 prints "2"



No comments:

Post a Comment

 

PHP and tips|PHP