Simple registry and globals

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

Post Reply
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Simple registry and globals

Post by alex.barylski »

Edit: Read the docs at PHP.net changed my source...looks like now I just need to assign by reference when I use an object from the registry to make sure I'm always using the actual object and not it's copy.??? :)

I'm creating this at the global level then just bringing it into local scope as needed using

Code: Select all

global $gRegister;
Obviously, I would like each object added/retreived to be the actual object and not a copy of the object (PHP4 default behavior) so I use references. Adding the object is obvious, simply put '&' next to the argument, do I again have to assign that object via reference when setting the regiter member variables?

What about when retreiving the object, do I use reference again like:

Code: Select all

$obj = &$gRegister->getObject('blah');

Code: Select all

//
  // Implement a trivial registry object
  class Spectra_Registry{
    function addObject($key, &$obj){ $this->_objects[$key] = &$obj; }
    function &getObject($key){ return $this->_objects[$key]; }

    // PRIVATE:
    var $_objects = null;
  }
Sorry feyd, I know I asked this almost same question a few days ago, but I've tried everything and passing objects around by reference is proving to be a PITA...hoping someone can shed some light on where and when (and hopefully why) I should use references :)

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

Post by feyd »

As I suggested before, it doesn't hurt to continue using the reference operator..
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post by stereofrog »

In php4, object variables should always be passed/returned by reference, unless you want to make a copy of some object. In php5, object variables are implemented as pointers and there's no need to use references anymore.
Post Reply