php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #38011 suggest $foo = &new Bar(); for PHP4
Submitted: 2006-07-05 01:18 UTC Modified: 2006-07-05 16:05 UTC
From: joliver at gmx dot at Assigned:
Status: Not a bug Package: Documentation problem
PHP Version: Irrelevant OS: all
Private report: No CVE-ID: None
 [2006-07-05 01:18 UTC] joliver at gmx dot at
Description:
------------
Please provide an advice to PHP4 users to use
$foo = &new Bar(); 
instead of $foo = new Bar(); 

Contrary to the examples in the documentation, in PHP4 
instances of objects should be initialisised with

$foo = &new Bar();

because here $foo is a reference to the created instance 
of Bar, while for

$foo = new Bar();

$foo is a copy(!) of the instance.

Appart from performance and memory issues, in the second 
case parameters in the constructors will be copied to, 
because the whole object is copied. That means for 
example, that for:

$foo = new Bar($this) 

$foo is an instance of Bar where $this is not the owner of 
that instance any more, because $foo is a copy of the 
newly created instance.

Good example in german: 
http://www.usegroup.de/software/phptutorial/klassen_und_objekte.html#ref_owner

Reproduce code:
---------------
<?php

class myC1
{
  var
    $greeting;
  var  $theC2;
  function sayHello()
  {
      echo $this->greeting;
  }
  function myC1()
  {
      $this->greeting="Howdy";
      $this->theC2=new myC2($this);
  }



}

class myC2
{
  var $owner;
  function myC2(&$owner)
  {
    $this->owner=&$owner;
    $this->owner->greeting="bah";
  }
  function something()
  {
    $this->owner->greeting="hulla";
    // This is supposed to change myC1's greeting to hulla, overwriting "bah".
  }
 }


$test=new myC1(); //$test=&new myC1();
$test->theC2->something();
$test->sayHello();

?>

Expected result:
----------------
$test=&new myC1();

returns the excepted result in PHP4. Please provide that 
advice for PHP4 users in the documentation.

Actual result:
--------------
As described above, $test=new myC1(); returns a copy of 
the instance, therefore $this in myC1 gets lost.

An advice for PHP4 users would be helpful, in my opinion 
in PHP4 
$foo=&new Bar(); should be used instead of 
$foo=new Bar(;), which is not mentioned anywhere in the 
documentation.

(of course i know in PHP5 this as been fixed because 
objects are passed by reference.)

Thank you!
Oliver

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2006-07-05 16:01 UTC] colder@php.net
There is already an explanation in the section about references:

http://php.net/language.references.whatdo
 [2006-07-05 16:05 UTC] colder@php.net
Sorry about the summary reset, it seems my form auto-completion went crazy ;)
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Mon Jul 07 19:01:34 2025 UTC