Skip to content
Advertisement

How to get class from a constant array?

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?

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement