NYCPHP Meetup

NYPHP.org

[nycphp-talk] Setting up PHP 4 OOP to work in PHP 5 environment

csnyder chsnyder at gmail.com
Thu Feb 24 09:58:02 EST 2005


On Thu, 24 Feb 2005 09:14:50 -0500, Randal Rust
<rrust at r2communications.com> wrote:
> csnyder wrote:
> 
> > Out of curiousity, why are you assigning by reference ( =& ) when
> > creating the new objects?
> 
> i was under the impression that =& created a new instance of the object,
> and that was the proper way to do it.
> 
> > Is it because DB, Display, and Validator implement a singleton pattern?
> 
> unfortunately, i have no idea what 'singleton patter' means:)
> 


A singleton is a class which returns an instance of some object. If
the instance doesn't exist yet, the singleton creates it. Otherwise, a
reference to the existing instance is returned. It's good for things
like database connections that you only need one of.

But that's beside the point... you don't need the =&, you can just say:
  $instance = new className;

>
> i am merely a designer learning to move from procedural scripting to
> OOP. so all i know is that in order to access the properties and methods
> in the other classes, i had to use a constructor.
> 

If you have a lot of classes that instantiate the same objects over
and over on construction, you might consider something like:

class Employer {
  function Employer() {
    global $DB;
    $this->db =& $DB;
  }
}

$DB = new DB;
$employer = new Employer;

The global command brings the previously created $DB object into the
local scope of the constructor. And you *would* use =& here so that
you create a reference (memory pointer) to the $DB object instead of a
copy of it.



More information about the talk mailing list