在PHP和JavaScript之间共享常量 [英] Share Constants Between PHP and JavaScript
问题描述
我正在开发的PHP应用程序中有几个常量。我已经定义了一个Constants类,并将常量定义为const VAR_NAME = value;在这堂课上。我想在JavaScript和PHP代码之间共享这些常量。是否有DRY(不要重复自己)机制来共享它们?
I have several constants in a PHP application I'm developing. I've defined a Constants class and the defined the constants as const VAR_NAME = value; in this class. I would like to share these constants between my JavaScript and PHP code. Is there a DRY (Don't Repeat Yourself) mechanism to share them?
class Constants {
const RESOURCE_TYPE_REGSITER = 2;
const RESOURCE_TYPE_INFO = 1;
}
推荐答案
我会用 json_encode
。您必须首先将类转换为关联数组。
I would use json_encode
. You will have to convert the class to an associative array first.
$constants = array("RESOURCE_TYPE_REGISTER"=>2, "RESOURCE_TYPE_INFO"=>2);
echo json_encode($constants);
如果您更喜欢使用类,也可以使用反射将类转换为关联数组。
You could also use reflection to convert the class to an associative array if you would prefer to use a class.
function get_class_consts($class_name)
{
$c = new ReflectionClass($class_name);
return ($c->getConstants());
}
class Constants {
const RESOURCE_TYPE_REGSITER = 2;
const RESOURCE_TYPE_INFO = 1;
}
echo json_encode(get_class_consts("Constants"));
这篇关于在PHP和JavaScript之间共享常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!