Skip to content

Cannot directly modify an object stored in a constant #10497

@claudepache

Description

@claudepache

Description

The following code:

<?php
const a = new stdClass;
a->b = 42;
var_dump(a);

Resulted in this output:

Fatal error: Cannot use temporary expression in write context in /tmp/preview on line 3

But I expected this output instead:

object(stdClass)#1 (1) {
  ["b"]=>
  int(42)
}

(The issue also arises for objects stored in class constants.)

A workaround is to use a temp variable (because a temporary variable is not a “temporary expression”, eh):

<?php
const a = new stdClass;
$_ = a;
$_->b = 42;
var_dump(a); // it works

Another workaround is to use a function returning the value of the constant:

<?php
const a = new stdClass;
constant('a')->b = 42;
var_dump(a); // it works

PHP Version

PHP 8.2

Operating System

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions