php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #76187 Assigning new object in ref-parameter: fn($obj = new stdClass()) raises notice
Submitted: 2018-04-05 14:58 UTC Modified: 2018-04-25 02:43 UTC
From: matthes at leuffen dot de Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 7.2.4 OS:
Private report: No CVE-ID: None
 [2018-04-05 14:58 UTC] matthes at leuffen dot de
Description:
------------
Notice is falsely triggered. The two examples should be the same.

Test script:
---------------
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);

// Function with reference parameter
function fn (&$obj) {}

fn($obj = new stdClass());   // <- Triggers notice: Only variables should be passed by reference

// ... should be the same as ...

$obj = new stdClass();
fn($obj);                    // <- No warning


Expected result:
----------------
No notice

Actual result:
--------------
Notice: Only variables should be passed by reference in xxx

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-04-05 15:01 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2018-04-05 15:01 UTC] requinix@php.net
$obj=new stdClass() is an expression and expressions cannot be passed by reference.
 [2018-04-25 02:22 UTC] a at b dot c dot de
To be specific, "$obj = new stdClass()" is an expression that evaluates to the value on its right-hand side; as a side effect it also sets the variable on the left to that value.

So when it's used in a larger expression, the larger expression gets the value (in this case, a new stdClass object), not the variable.
 [2018-04-25 02:43 UTC] requinix@php.net
It doesn't matter than the RHS of the assignment was an expression - it's the entire assignment itself that's the problem. So even if the RHS is a variable,
  fn($obj = $var);
it will not work.
 [2018-07-29 05:13 UTC] a at b dot c dot de
Yes; the whole assignment is what I meant by "the expression"; its value is that of its RHS. Assignment expressions are not variables.

In the original, the value is the new object; in your version the value is that of $var (and not, for instance the variable $var itself). And $obj plays no part in the value in either case.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 12:01:27 2024 UTC