1

I've read about this interesting syntax in PHP:

$value = (new MyClass)->attribute1;
  1. Is it ok to use it? I've never seen anything like this in any code I've analyzed. Any pros and cons?
  2. Why can't I set the attribute using this syntax? Structures like this:

    (new MyClass)->attribute1 = 'value1';

throw errors at '=' sign, no matter if the attribute exists in the class already.

1
  • That syntax is valid since php version 5.4 according to the documentation. Commented Nov 11, 2012 at 13:05

2 Answers 2

2
  1. Well i don't see the point of using it since you loose your reference to the object, you cannot use it anymore, and it breaks the OO concept.

  2. I think (new MyClass)->attribute1 is resolved first, so it is the same as writing something like 42 = 12

Sign up to request clarification or add additional context in comments.

Comments

0

This may have a sense, if the class MyClass supports internal static list (or hashmap) of all existing instances. This way you can create new object and get its unique ID or index in the list for future references (for example, by sending it via cookies to a client).

As for assignment, you'd post exact error message for this case. I can guess, that the error is about assigning something to a temporary value which is about to be destroyed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.