【问题标题】:How to get class from a constant array?如何从常量数组​​中获取类?
【发布时间】:2021-08-11 17:33:28
【问题描述】:

我有大约 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 arrays constants


【解决方案1】:

我不知道你为什么会,但是你可以:

<?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);

【讨论】:

  • 这看起来比 php8.0 附加括号解决方案差,但它适用于 php
猜你喜欢
  • 2019-09-30
  • 1970-01-01
  • 2020-01-19
  • 2013-07-25
  • 2021-08-19
  • 2011-02-21
  • 2021-05-13
  • 2011-05-07
  • 1970-01-01
相关资源
最近更新 更多