1

I'm just curious if it's possible to get the value of a class variable when making an object of it? What I'd like to do is:

$class = new MyClass("something")->ok;

For the example above, the class is:

class MyClass {
   public $ok;

   public function __construct($a) {
      $this->ok = $a;
   }
}

I know it's easy to get the value of $a by writing one more line, but I'm really curious if it's possible to do in a shorter way.

0

1 Answer 1

2

Yes, it is possible. This feature is known as "Instance method call" and was introduced in PHP 5.4. Just include a pair of extra parentheses wrapping the new MyClass() expression:

$class = (new MyClass("something"))->ok;
         ^                        ^

The expression new MyClass() is what returns the object (as opposed to the class constructor), which is why it requires to be wrapped in an extra pair of parentheses.

More reading:

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

2 Comments

So easy and clever solution, thank you! I used Class as the name of the class for example only, but I should've used something else, you're right. :)
@KissKoppány: Glad to have helped. Cheers!

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.