views:

111

answers:

1

hello,

i asked this in the mongodb user-group, but was not satisfied with the answer, so -- maybe someone at stackoverflow can enlighten me:

EDIT:

i've re-written my question, because apparently it wasn't clear, what was happening -- please try my test-code before answering. thanks!

<?php

// test: a
$data = array('x' => 1);

function a(&$data) {
    $m = new mongo();
    $c = $m->selectDB('test')->selectCollection('test');

    $c->insert($data);
}

a($data);
print_r($data);

// test: b
$data = array('x' => 1);

function b($data) {
    $m = new mongo();
    $c = $m->selectDB('test')->selectCollection('test');

    $c->insert($data);
}

b($data);
print_r($data);

// test: c
$data = array('x' => 1);

function c(&$data) {
    $data['_id'] = new MongoId();
}

c($data);
print_r($data);

// test: d
$data = array('x' => 1);

function d($data) {
    $data['_id'] = new MongoId();
}

d($data);
print_r($data);

?>

output:

Array
(
    [x] => 1
)

Array
(
    [x] => 1
    [_id] => MongoId Object
        (
        )

)

Array
(
    [x] => 1
    [_id] => MongoId Object
        (
        )

)

Array
(
    [x] => 1
)

my question: why does pass-by-reference apparently work different for mongo insert compared to my plain php function call?

thanks!

A: 

When you have something like $ref = &$someVar. $ref now refers to the value at $someVar.

EDIT:

The MongoDB Manual at PHP.net says:

Example #1 MongoCollection::insert() _id example Inserting an object will add an _id field to it, unless it is passed by reference.

<?php

$a = array('x' => 1);
$collection->insert($a);
var_dump($a)

$b = array('x' => 1);
$ref = &$b;
$collection->insert($ref);
var_dump($ref);

?>
Babiker
yes i know. if i then pass $ref to a function, which accepts the parameter as reference (like my test function), than $ref ($someVar) can be enhanced with more data. ... but the mongodb-insert does not work this way. my question: why does the mongodb-insert method behaves like it behaves?
harald
babiker, i understand, what the documentation is telling me. thanks for your help, but it does not answer my question: i don't understand the sense behind this behaviour. who is doing the magic behind the scenes? who keeps the _id out of $ref and why does this behaviour differ from the behaviour of my plain php test?
harald