...

View Full Version : Classes/References problem



FoxyForest
03-16-2007, 08:00 PM
This issue is best explained by code.

The var_dump inside getchiefstomach shows NULL. What it 'should' show is a reference to the stomach object inside the cow object. Why is it NULL? Setting the value instead of a reference works, but is not ideal.


<?php
class herd
{
public $chiefcow;

function getchiefstomach()
{
$this->chiefcow->stomach($s);
var_dump($s);
}
}

class cow
{
public $stomachs = array();

function stomach(&$st)
{
//Changing this to '=' 'fixes' it, but presumably passes the value of $stomachs[0], not a reference to it, which is what I am trying to achieve.
$st =& $this->stomachs[0];
}
}

class stomach
{
}

$daisy = new cow();
$daisy->stomachs[] = new stomach();
$daisy->stomachs[] = new stomach();

$herdy = new herd();
$herdy->chiefcow =& $daisy;
$herdy->getchiefstomach();
?>

This is in PHP5 btw.

aedrin
03-16-2007, 08:27 PM
//Changing this to '=' 'fixes' it, but presumably passes the value of $stomachs[0], not a reference to it, which is what I am trying to achieve.

Classes (or objects) are passed by reference by default (starting from PHP 5 I believe).

If you're using an older version, then I'm not sure why it would end up as null.

Change it to just have an equal sign, modify it and see whether it was a copy, or a reference.

(Interesting classes by the way, I am guessing this is just to explain it?)

FoxyForest
03-16-2007, 09:23 PM
Heh, yeah, I always use daft stuff for tests. Helps keep my mood up when banging my head against the wall. :p

aedrin
03-16-2007, 10:57 PM
Hehe. For a moment I was trying to figure out what this could be for.

I was thinking of some sort of simulation website for education ;)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum