Page 2 of 2

Posted: Mon Jul 10, 2006 8:32 am
by feyd
You guys may want to know that the two classes will create an infinite recursion in class creations. PHP will notice and stop it.

Each respective class creates an instance of the other. This starts the recusion. As each one is created, the other must be created too.

Use a basic composition model instead.

Code: Select all

<?php
class Test
{
        private $testing;
       
        public function __construct ()
        {
        }

        public function setTesting ($testing)
        {
                $this->testing = $testing;
        }
}

class Testing
{
        private $test;

        public function __construct ()
        {
                $this->test = new Test();
        }

        public function setTest ($test)
        {
                $this->test = $test;
        }
}

$test = new Test();
$testing = new Testing();
$test->setTesting($testing);
$testing->setTest($test);
?>
The problem is, the original concept promotes really nasty coupling. If they are that integrated, you may want to consider building them together or rethinking their interactions more carefully.

Posted: Mon Jul 10, 2006 9:53 am
by Jenk
And the fog clears.. one of those "why didn't I see that already?" moments.

Posted: Mon Jul 10, 2006 10:33 am
by kahwooi
Thanks feyd, and everyone who reply. Thank you. Is it good to use superglobals like the example below?

$test = new test();

class Testing{
public function setTest(){
$test = $GLOBALS['test'];
}
}

Posted: Mon Jul 10, 2006 10:56 am
by Jenk
Globals within a class/object are usually a nono. what happens if $test is not defined in the global scope?

feyd's example is the best method - use a setter.

Posted: Mon Jul 10, 2006 2:39 pm
by Chris Corbyn
Jenk wrote:Globals within a class/object are usually a nono. what happens if $test is not defined in the global scope?

feyd's example is the best method - use a setter.
Some people use globals to hack a way of creating a singleton. It's better to use static properties, but some would argue that (for the sake of testing) singletons should be avoided at all.