0

I have about twenty different classes that are segregated in an assoc array similar to this:

class a {public $val = 1;}
class b {public $val = 2;}
$classes = array("one"=>'a', "two"=>'b');
var_dump(new $classes["one"]()); // object(a)#1 (1) { ["val"]=> int(1) }
var_dump(new $classes["two"]()); // object(b)#1 (1) { ["val"]=> int(2) }

But now I want to do the array constant.

I can make it using const VAL = array(); just fine. The problem lies in making new objects using those classes

class a {public $val=1;}
class b {public $val=2;}
const CLASSES = array("one"=>'a', "two"=>'b');
var_dump(new CLASSES["one"]());

fails with Parse error: syntax error, unexpected '[', expecting ')' error.

I figured that I could reverse const array to variable again and it works fine:

class a {public $var = 1;}
class b {public $var = 2;}
const CLASSES = array("one"=>'a', "two"=>'b');
$tempClasses = CLASSES;
var_dump(new $tempClasses["one"]()); // works

but why doesn't it work with a constant array?

I tried playing with parenthesis and constant() too. Neither new (CLASSES)["one"](), new (CLASSES["one"])(), new constant(CLASSES)["one"]() nor new constant(CLASSES["one"])() work.

Is there something I'm missing?

7
  • 3
    new (CLASSES["one"])() works in PHP 8+. Demo: 3v4l.org/BUJ8H. Otherwise, you can do $one = CLASSES['one']; new $one(); in all versions. Demo: 3v4l.org/89PP3 Commented Aug 11, 2021 at 17:45
  • so it wasn't implemented before... that sucks. Commented Aug 11, 2021 at 17:52
  • I don’t know what you are exactly doing, but your code looks like it is going down an enum-like path which is coming in 8.1 and has existing support using many libraries, including this Commented Aug 12, 2021 at 1:47
  • If you aren’t going down enum path, this feels like a general factory pattern decide Commented Aug 12, 2021 at 1:48
  • stackoverflow.com/q/20278476/2943403 , stackoverflow.com/q/534159/2943403 Commented Aug 12, 2021 at 4:22

1 Answer 1

1

I don't know why you would, but yes you can:

<?php

class a {public $val=1;}
class b {public $val=2;}
const CLASSES = array("one"=>'a', "two"=>'b');


$obj = (new ReflectionClass(CLASSES["one"]))->newInstance();

var_dump($obj);
Sign up to request clarification or add additional context in comments.

1 Comment

That looks way worse than php8.0 additional parenthesis solution, but it works for php<8.0 so thanks! I just changed to php8.0

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.