我可以在一个类中设置一个常量,然后在PHP外部访问它吗? [英] Can I set a constant in a class then access it outside in PHP?
问题描述
我试图在类的内部初始化一些值,并将其保存为常量,然后在代码的不同部分访问它们。
I am trying to initialize some values inside a class and save them in constant and access them outside, in different part of my code.
<?php
class Config {
public static function initialize() {
define('TEST',"This is a Constant");
}
}
$config = Config::initialize();
// do something with the constants
我可以在外部访问它吗?
Can I access it outside?
推荐答案
Class常量使用 const
关键字。您无需使用define函数对其进行定义。就像这样:
A Class constant uses the const
keyword. You don't define them using the define function. Just like this:
class Config {
const TEST = "This is a constant";
}
// then use it:
var_dump(Config::TEST);
在PHP中,您无法动态设置常量的值,但是可以通过以下方式获得类似的行为公共静态变量。
In PHP, you cannot dynamically set the value of a constant, but you can get a similar behaviour with a public static variable. ie.
class Config2 {
public static $test = null;
public static function initialize()
{
self::$test = "This is not a constant";
}
}
// Then use like
Config2::initialize();
var_dump(Config2::$test);
缺点是,没有什么可以阻止其他代码从类外部设置值。如果需要对此进行保护,则应使用吸气剂功能方法。
The downside is, there is nothing stopping other code from setting the value from outside the class. If you need protection against this, you should use a getter function approach. eg.
class Config3 {
private static $_test = null;
public static function initialize()
{
self::$_test = "This is not a constant, but can't be changed outside this class";
}
public static function getTest()
{
return self::$_test;
}
}
// Then use like
Config3::initialize();
var_dump(Config3::getTest());
这篇关于我可以在一个类中设置一个常量,然后在PHP外部访问它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!