Reputation: 950
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.
Upvotes: 1
Views: 40
Reputation: 76656
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:
Upvotes: 2