arc_of_descent has asked for the wisdom of the Perl Monks concerning the following question:


Hi Monks

I have created 2 objects called Customer and Debug. They are very simple (for purpose of testing), having just a constructor and some simple methods. Now in my main program cust.pl, I instantiate the 2 objects as $cust and $debug. From cust.pl, I can easily access methods of $debug object. Now how do I access this $debug object from inside the methods of $cust object?

One way is to pass the $debug object as a constructor
or maybe even per method argument. But that looks like too much of work. Am I missing something simple here?
I would very much appreciate any help in the form of links or some usefeul hints/feedback.

--
arc_of_descent

  • Comment on Accessing an instantiated object from another .pm file

Replies are listed 'Best First'.
Re: Accessing an instantiated object from another .pm file
by castaway (Parson) on Oct 15, 2003 at 11:21 UTC
    The OO way would be to pass the $debug object to $cust somehow, ie $cust->setDebuggingObject($debug), this may sound like work but it pays off if you do it properly..

    Another way would be just to call ::main::debug->method(args) from inside your $cust object, but this would be making the Customer object dependent upon the main having such an object, and saving it under this name. (if you later decided to change the instance of the Debug object to be called $mydebug, you'd have to change Customer as well.)

    A third slightly similar way would be to have Customer call a function in main, which returns it the debug object, whenever it needs it. (In Customer) my $debugobj = ::main::getDebugObj();, but this is again dependent upon main implementing this method.. (Ok, its your main, but what if someone else used your classes?).

    Fourth: (While I think of it) - Have a common Id in Customer and Debug, and keep references to the Debug objects in the Debug class. Now Customer can ask Debug directly for a specific Debug object. (it's still kinda backwards though :). my $debugobj = Debug::getDebugObj($me->debugID); (or something..)

    Lastly, something like debugging can usually be done with a Singleton, ie one single object that handles debugging, instead of instanciating lots of debug objects. (Tho I guess your question was more general than that..)

    C.