Php syntax. How to combine 2 lines into one expression?

As the bottom 2 lines to write one?

<?php
class MyClass2{
 public $var = 123;
}
class MyClass{
 public $var;
 function __construct(){
 $this--->var = function(){
 return new MyClass2();
};
}
}
function myFunc(){
 return new MyClass();
}

$var = myFunc()->var;
echo $var()->var;
July 2nd 19 at 18:06
3 answers
July 2nd 19 at 18:08
Solution
(myFunc()->var)()->var
Have you tried? Works for you?
I did so, I have a Pars error. - Davonte.Renner commented on July 2nd 19 at 18:11
: I have to PHP7 everything works - vito.Hoeg commented on July 2nd 19 at 18:14
:
➜ ~ php-v
PHP 7.0.8 (cli) (built: Jun 23 2016 16:32:40) ( NTS )
Copyright (c) The PHP Group 1997-2016
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
- vito.Hoeg commented on July 2nd 19 at 18:17
tested on 7 rabotaet - Mitchell_Zemlak16 commented on July 2nd 19 at 18:20
Yes the seven is not the test, I'll try. - Davonte.Renner commented on July 2nd 19 at 18:23
July 2nd 19 at 18:10
as an option to rewrite the class
class MyClass2{
 public $var = 123;
}
class MyClass{
 public $var;
 function __construct(){
 $this->var = new MyClass2();
}
}
function myFunc(){
 return new MyClass();
}

echo myFunc()->var->var;
I just simplified the example, I need there is an anonymous function. - Davonte.Renner commented on July 2nd 19 at 18:13
July 2nd 19 at 18:12
I suspect that like so:
echo myFunc()->var()->var;
no - Davonte.Renner commented on July 2nd 19 at 18:15
Will be called by the class method, which is not. What I don't need. - vito.Hoeg commented on July 2nd 19 at 18:18

Find more questions by tags PHP