Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Jul 2006
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Classes/References problem

    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 Code:
    <?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.
    Last edited by FoxyForest; 03-16-2007 at 10:23 PM.

  • #2
    Senior Coder
    Join Date
    Jan 2007
    Posts
    1,648
    Thanks
    1
    Thanked 58 Times in 54 Posts
    //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?)

  • #3
    New Coder
    Join Date
    Jul 2006
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Heh, yeah, I always use daft stuff for tests. Helps keep my mood up when banging my head against the wall.

  • #4
    Senior Coder
    Join Date
    Jan 2007
    Posts
    1,648
    Thanks
    1
    Thanked 58 Times in 54 Posts
    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


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •