php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #7454 $this in constructor is different than instaniated object
Submitted: 2000-10-25 12:59 UTC Modified: 2000-12-06 16:47 UTC
From: heathmike at hotmail dot com Assigned:
Status: Closed Package: Class/Object related
PHP Version: 4.0.3 OS: RedHat 6.2
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: heathmike at hotmail dot com
New email:
PHP Version: OS:

 

 [2000-10-25 12:59 UTC] heathmike at hotmail dot com
Trying to store a reference to $this from inside the constructor does not store the same reference that new class() returns.  The following example shows that.

<?php

class foo {
  var $Name;
  function foo($name) {
    Global $List;
    $List[] = &$this;
    $this->Name = $name;
  }
  function echoName() {
    echo "<br>".$this->Name;
  }
}

$bar1 = new foo('constructor1');
$bar2 = new foo('constructor2');
$bar3 = new foo('constructor3');

$bar1->Name = 'outside1';
$bar2->Name = 'outside2';
$bar3->Name = 'outside3';

// $bar1..3 have been changed as shown below

$bar1->echoName();
$bar2->echoName();
$bar3->echoName();

// $list however contains a copy becuase it's values have not been changed

while (list($key, $val) = each($List)) {
  $val->echoName();
}

?>

Either a copy is being made when it shouldn't be or I'm doing something wrong.  If I'm doing something wrong I think this should be documented.

Mike Heath

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2000-11-27 07:17 UTC] sniper@php.net
reclassify

 [2000-11-27 14:53 UTC] waldschrott@php.net
simplified and extended testcase

<?php
class foo {
	function foo($name) {
    	$GLOBALS['List']= &$this;
    	$this->Name = $name;
		$GLOBALS['List']->echoName(); }

	function echoName() {
    	echo "<br>".$this->Name; } }

function &foo2(&$foo)	{
	return $foo; }


$bar1 = new foo('constructor1');
//$bar1 = foo2(new foo('constructor1'));

$bar1->Name = 'outside1';


$bar1->echoName();
$List->echoName();
echo '<P>';

?>
 [2000-12-06 16:47 UTC] waldschrott@php.net
fixed in latest CVS, but you'll have to use

$bar1 = &new foo('constructor1');
$bar2 = &new foo('constructor2');
$bar3 = &new foo('constructor3');

in these cases instead, please check it out

 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Feb 23 08:01:29 2024 UTC