Class __construct

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

And the fog clears.. one of those "why didn't I see that already?" moments.
kahwooi
Forum Commoner
Posts: 25
Joined: Fri Dec 10, 2004 12:28 am

Post 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'];
}
}
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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.
Post Reply