如何从常量数组中获取 class?
How to get class from a constant array?
我有大约 20 个不同的 类 被隔离在一个类似这样的关联数组中:
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) }
但是现在想做数组常量
我用const VAL = array();
就可以了。
问题在于使用 类
制作新对象
class a {public $val=1;}
class b {public $val=2;}
const CLASSES = array("one"=>'a', "two"=>'b');
var_dump(new CLASSES["one"]());
失败并出现 Parse error: syntax error, unexpected '[', expecting ')'
错误。
我想我可以再次将 const 数组反转为变量并且它工作正常:
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
但为什么它不适用于常量数组?
我也试过使用括号和 constant()
。 new (CLASSES)["one"]()
、new (CLASSES["one"])()
、new constant(CLASSES)["one"]()
和 new constant(CLASSES["one"])()
都不起作用。
有什么我遗漏的吗?
我不知道你为什么会这样做,但是你可以:
<?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);
我有大约 20 个不同的 类 被隔离在一个类似这样的关联数组中:
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) }
但是现在想做数组常量
我用const VAL = array();
就可以了。
问题在于使用 类
class a {public $val=1;}
class b {public $val=2;}
const CLASSES = array("one"=>'a', "two"=>'b');
var_dump(new CLASSES["one"]());
失败并出现 Parse error: syntax error, unexpected '[', expecting ')'
错误。
我想我可以再次将 const 数组反转为变量并且它工作正常:
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
但为什么它不适用于常量数组?
我也试过使用括号和 constant()
。 new (CLASSES)["one"]()
、new (CLASSES["one"])()
、new constant(CLASSES)["one"]()
和 new constant(CLASSES["one"])()
都不起作用。
有什么我遗漏的吗?
我不知道你为什么会这样做,但是你可以:
<?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);