php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #49962 Reassign an object inside function
Submitted: 2009-10-22 18:16 UTC Modified: 2009-10-23 12:11 UTC
From: diego at ditech dot com dot br Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 5.2.11 OS: Windows XP SP3
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 you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: diego at ditech dot com dot br
New email:
PHP Version: OS:

 

 [2009-10-22 18:16 UTC] diego at ditech dot com dot br
Description:
------------
When trying to reassign an object inside a function, it is not acting as passed by reference.

Reproduce code:
---------------
<?php
class foo {
}

function change($obj) {
  $obj = null;
}

function change_ref(&$obj) {
  $obj = null;
}

$o = new foo;

change($o);
var_dump($o);

change_ref($o);
var_dump($o);

Expected result:
----------------
Both should yield the same result.

1st: NULL
2nd: NULL

Actual result:
--------------
Only change_ref is redefining the object.

1st: 
object(foo)#1 (0) {
}

2nd: NULL

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-10-22 18:28 UTC] diego at ditech dot com dot br
By the way, it is possible to change object attributes as if both were passed by reference.

class foo {
  public $bar;
}

function change($obj) {
  $obj->bar = 1;
  $obj = null;
}

$o = new foo;
change($o);
var_dump($o);

The result of this is:
object(foo)#1 (1) {
  ["bar"] => int(1)
}
 [2009-10-23 12:11 UTC] jani@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php


 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Mar 12 11:01:32 2025 UTC