[UPHPU] oop :B

Fred Larsen fred at bitwyze.com
Fri May 14 11:57:31 MDT 2004


On Fri, 14 May 2004, David Smith wrote:

> <quote who="Fred Larsen">
> > You might want to make a small change to your script.
> >
> > class Test {
> > 	var $db_conn;
> >
> > 	function Test(&$db_conn) {
> > 		$this->db_conn = &$db_conn;
> > 	}
> > }
> >
> > The "&" in the constructor is called passing my reference.  A reference to
> > the $db_conn var is passed to the function. If you do not include the "&"
> > PHP will make a copy of the $db_conn var when you call the constructor.
> 
> This is not exactly true. If you omit the '&', PHP does not actually make
> a copy of the variable until the variable is modified. This is called
> "copy on write" and it is actually faster than passing by reference.
> According to _Programming PHP_ (written by Rasmus himself), if you are
> passing variables that will be read only and likely not changed, it is
> faster even for arrays and objects to _not_ pass by reference thanks to
> the brilliance of copy on write. Use pass-by-reference for reasons other
> than performance, cause performance isn't improved by passing by reference
> in PHP.
> 

You are absolutely correct.

The constructor will not make a new copy of $db_conn.  However, if do call
$this->db_conn->query(), which is probaby why you want to add this to your
class in the first place, PHP will most likely make a copy.  This is
because $this->db_conn->query() most of the time modifies the
$this->db_conn->last_query member var when it is called.

Fred




More information about the UPHPU mailing list