2

When I run the following code,

<?php

const nums = [1, 2, 3];
nums[0] = 50;

it gives me the following error:

Fatal error: Cannot use temporary expression in write context in <file> on line 4

My question is what exacty is a temporary expression in PHP? I've tried searching the documentation of PHP for an answer but there is nothing mentioned there regarding this error.

I just can't understand what exactly does this error mean?

coderboy
  • 1,710
  • 1
  • 6
  • 16
  • `nums` is const. Modifying it defeats the point – apokryfos Jun 29 '23 at 08:08
  • I know that. I am trying to make intuition of the error message. – coderboy Jun 29 '23 at 08:09
  • 2
    FWIW, PHP error messages sometimes tend to be obscure and nonsensical. It's referring to some internals which shouldn't really matter to you. The error is that you're trying to modify a constant, which you simply can't. The error message just does a terrible job telling you that. — Still an interesting question about PHP internals, if that's what you're after… – deceze Jun 29 '23 at 08:09
  • your problem is because you're using ```const``` which means your array is now immutable and can't be changed, change your code to this: ```$nums = [1, 2, 3];``` – Daniel_Kamel Jun 29 '23 at 08:09
  • 3
    I'm guessing `nums[0]` is the temporary expression in question puting it on the left of an `=` puts it in "write context" – apokryfos Jun 29 '23 at 08:10
  • @Jens I tried reading that question and its answer but it's something unrelated to my question. – coderboy Jun 29 '23 at 08:13
  • I suppose not assigning to a *variable* starting with `$` is always an error. Expression like `foo[bar]` are apparently "temporary expressions" in PHP because… internals. Having those appear on the left hand side of a `=` is the error. – deceze Jun 29 '23 at 08:14
  • Ok, can we close this question now? – nice_dev Jun 29 '23 at 09:00
  • https://stackoverflow.com/a/40540148/487813 also may be helpful – apokryfos Jun 29 '23 at 11:04

1 Answers1

2

This message is a bit of a leaked internal. If you look for the string in PHP source code, you'll find explicit unit tests that illustrate the error being thrown in these contexts:

  • Enum prevent unsetting value

    enum Foo: int {
        case Bar = 0;
    }
    
    unset(Foo::Bar->value);
    
  • Passing a dimension fetch on a temporary by reference is not allowed

    $fn = function(&$ref) {};
    $fn([0, 1][0]);
    
  • Passing a property fetch on a temporary by reference is not allowed

    $fn = function(&$ref) {};
    $fn([0, 1]->prop);
    
  • Writing to a temporary expression is not allowed

    [0, 1][0] = 1;
    

The message is confusing because it isn't directly triggered by writing to a constant. In fact, FOO = 2; alone is a parse error.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360