Tag vite :

PHP function arguments by reference

 Posté par greg le 1 février 2012 08:35 |  Les commentaires sont désactivés pour ce post.
Tags : geek  computing  dev  php 

A short article on PHP function arguments

Everyone knows since PHP5, objects are passed by reference to the functions and methods. That mean modifying an object in a function modifies directly the data pointed by the variables.

<?php

class A
{
    public $data;
}

function modifyA(A $instance)
{
    $instance->data = 1000;
}

$a = new A();
$a->data = 0;
modifyA($a);
echo $a->data; // 1000

As the local variable $instance and $a point internally to the same data structure in memory, modifying $instance is the same as modifying $a. Adding a & front of the $instance declaration in function signature forces PHP to pass data as reference and should have exactly the same results.

Have now a look at the following code, you will understand it is not the case:

<?php

class A
{
    public $data;
}

function modifyA(A $instance)
{
    if ($instance->data === 0) {
        $instance = new A();
    }

    $instance->data = 1000;
}

$a = new A();
$a->data = 0;
modifyA($a);
echo $a->data; // 0
modifyA(&$a);
echo $a->data; // 1000

Hope that will save you some time.

Liens récents 

 Crew - code review for Git projects.

Marqué par greg le 6 mai 2012 07:57..
Tags: geek computing git

Suivre le lien

 responsive grid system

Marqué par greg le 5 mai 2012 12:38..
Tags: geek computing dev

Suivre le lien

 Vim "improved

Marqué par greg le 8 mars 2012 09:26..
Tags: geek computing vim

Suivre le lien

 Highly scalable NoSql blog

Marqué par greg le 3 mars 2012 09:12..
Tags: geek computing dev

Suivre le lien

 Bruce Momjian Pg blog

Marqué par greg le 16 février 2012 13:51..
Tags: geek computing postgresql net blog

Suivre le lien

 Richard Miller's blog

Marqué par greg le 16 février 2012 09:57..
Tags: geek computing dev php symfony net blog

Suivre le lien

 Online SQL explain interface

Marqué par greg le 15 février 2012 09:58..
Tags: geek computing postgresql net

Suivre le lien

 Ace online code editor

Marqué par greg le 15 février 2012 08:57..
Tags: net geek computing dev javascript

Suivre le lien

 Coding horror

Marqué par greg le 14 février 2012 12:42..
Tags: geek computing dev net blog

Suivre le lien

 telegraphCQ - Stream oriented database

Marqué par greg le 13 février 2012 14:44..
Tags: geek computing postgresql

Suivre le lien