0

So, I'm writing some code as part of a project which involves the use of anonymous classes. As part of the project's criteria, there is a need for an anonymous class to be imbedded inside another anonymous class. My code is as follows:

$foo = new class($a, $b, $c) {

    public $a;
    public $b;
    public $c;

    public function __construct($a, $b, $c) {
        $this->a = $a;
        $this->b = $b;
        $this->c = $c;
    };

    public $bar = new class($x) {

        public $x;

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

        public function __toString() {
            return $this->x;
        }

    };

}

As you can see from the code above, $bar is the anonymous class inside of anonymous class $foo. I get the following PHP error code when executing this code:

PHP Fatal error: Constant expression contains invalid operations

Any help would be appreciated. Anonymous classes are new to me (and PHP it appears).

Thanks.

Ryan Castle
  • 21
  • 1
  • 5
  • 2
    You can only assign constant values to a class property. Have a try setting `$bar` inside the outer class constructor. – arkascha Oct 25 '16 at 09:11
  • That error just refers to the missing `$` in front of `foo` (it thinks you're attempting to assign the result of the anonymous object to a constant... I think) - however I'm not running PHP 7 on my dev box so I can't test the rest of it. – CD001 Oct 25 '16 at 09:21
  • @CD001 - This error is in the snippet in StackOverflow, not my actual code. Thanks for flagging this issue. – Ryan Castle Oct 25 '16 at 09:25
  • Aaah, yeah I can see what @arkascha was saying now - brain not quite in gear yet :) – CD001 Oct 25 '16 at 09:28
  • Ran it on an online codepad - there are a few other syntax errors (missing `function` keyword and you need to add a semi-colon after the `public $bar = new class { }`) but with a little juggling about it does work : http://sandbox.onlinephpfunctions.com/code/620011a1ce4e819332774ff5af09650fa48ac1a6 (set it to PHP 7.x) – CD001 Oct 25 '16 at 09:41
  • Yea, the code written in the snippet isn't the best, I wrote it very badly aha. @arkascha's comment caused this to work. Thanks. – Ryan Castle Oct 25 '16 at 10:30

0 Answers0