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
 [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

Add a Patch

Pull Requests

Add a Pull Request

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-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 25 23:01:29 2024 UTC