Page 1 of 1

Simple registry and globals

Posted: Sat Mar 24, 2007 12:50 am
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 :)

Posted: Sat Mar 24, 2007 1:16 am
by feyd
As I suggested before, it doesn't hurt to continue using the reference operator..

Posted: Sat Mar 24, 2007 5:37 am
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.