百科狗-知识改变命运!
--

constant() - php 选项信息函数

乐乐1年前 (2023-11-21)阅读数 11#技术干货
文章标签常量

constant()

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

返回一个常量的值

说明

constant(string $name): mixed

通过$name返回常量的值。

当你不知道常量名,却需要获取常量的值时,constant()就很有用了。也就是常量名储存在一个变量里,或者由函数返回常量名。

该函数也适用class constants。

参数

$name

常量名。

返回值

返回常量的值。如果常量未定义则返回NULL

错误/异常

如果常量未定义,会产生一个E_WARNING级别的错误。

范例

constant() - php 选项信息函数

Example #1constant()的例子

参见

  • define() 定义一个常量
  • defined() 检查某个名称的常量是否存在
  • Constants这一节
The constant name can be an empty string.
Code:
define("", "foo");
echo constant("");
Output:
foo
If you are referencing class constant (either using namespaces or not, because one day you may want to start using them), you'll have the least headaches when doing it like this:


since F::class will be dereferenced to whatever namespace shortcuts you are using (and those are way easier to refactor for IDE than just plain strings with hardcoded namespaces in string literals)
It is worth noting, that keyword 'self' can be used for constant retrieval from within the class it is defined 
As of PHP 5.4.6 constant() pays no attention to any namespace aliases that might be defined in the file in which it's used. I.e. constant() always behaves as if it is called from the global namespace. This means that the following will not work:


However, calling constant('Foo::BAR') will work as expected.
Maybe this is useful:
$file_ext is the file Extension of the image 
Technically you can define constants with names that are not valid for variables:

Of course this is not a good practice, but PHP has got you covered.
When you often write lines like

to prevent errors, you can use the following function to get the value of a constant.

Finally you can check the value with

It's simply shorter.
To access the value of a class constant use the following technique. 
The use of constant() (or some other method) to ensure the your_constant was defined is particularly important when it is to be defined as either `true` or `false`. 
For example, taken from this Stackoverflow Question 
https://stackoverflow.com/questions/5427886/php-undefined-constant-testing/56604602#56604602)  
 If `BOO` did NOT get defined as a constant, for some reason,
  
would evaluate to `TRUE` and run anyway. A rather unexpected result.  
The reason is that PHP ASSUMES you "forgot" quotation marks around `BOO` when it did not see it in its list of defined constants.  
So it evaluates: `if ('BOO')`...  
Since every string, other than the empty string, is "truthy", the expression evaluates to `true` and the do_something() is run, unexpectedly. 
If you instead use: 
    
then if `BOO` has not been defined, `constant(BOO)` evaluates to `null`, 
which is falsey, and `if (null)`... becomes `false`, so do_something() is skipped, as expected.  
The PHP behavior regarding undefined constants is particularly glaring when having a particular constant defined is the exception, "falsey" is the default, and having a "truthy" value exposes a security issue. For example,  
 . 
There are other ways around this PHP behavior, such as  
 
or 
.  
Note that only the version using `defined()` works without also throwing a PHP Warning "error message."
Here is a php repl.it demonstration: 
https://repl.it/@sherylhohman/php-undefined-constants-beware-of-truthy-conversion?language=php_cli&folderId=
(disclosure: I also submitted an answer to the SO question linked to above)
// 1) you can store the name of constant in default variable
 //   and use it without identify it's name :)
    $str= "constName";
   
    define("constName","this is constant");
    echo constant($str);
    
    output:
       this is constant
// 2) good for dynamic generating constants
    
     function generateConst( $const , $value , $sensitivity=TRUE )
       {
       
          define( "$const" , "$value ",$sensitivity);
       }
       $CONST="cost";
       $VALUE="100$";
       
       generateConst( $CONST , $VALUE);
             
       echo constant($const);
    output:
        100$
You can define values in your config file using the names of your defined constants, e.g. 
in your php code:
define("MY_CONST",999);
in you config file:
my = MY_CONST 
When reading the file do this:
$my = constant($value); // where $value is the string "MY_CONST"
now $my holds the value of 999
In reply to VGR_experts_exchange at edainworks dot com
To check if a constant is boolean, use this instead:

Much quicker and cleaner than using defined() and constant() to check for a simple boolean.
IMO, using ($var === true) or ($var === false) instead of ($var) or (!$var) is the best way to check for booleans no matter what. Leaves no chance of ambiguity.
This function is namespace sensitive when calling class constants.
Using:

This does not seem to affect constants defined with the 'define' function. Those all end up defined in the root namespace unless another namespace is implicitly defined in the string name of the constant.
Checking if a constant is empty is bork... 
You cannot 
Return constants from an object. You can filter by regexp or match by value to find a constant name from the value.
Pretty useful sometimes.

Examples : 
It's easily to user constant() and define() to translate some words from your database-saves.
For example: 
You have a table userprofil and one coloumn is "gender".
Gender can be male or female but you will display "maennlich" or "weiblich" (german words for it - whatever...)
First step: Fetch into $Gender
Second:
define("male", "maennlich");
define("female", "weiblich");
Third:
echo constant($Gender);
Now, the index of the variable $Gender will be handled like a constant!
(It works like "echo male;" for better understanding)
And a result of this, it displays maennlich btw. weiblich!
greetz
ss
sssssss
ssssssssssssssssss
s
ssssssssssssss
ssssssssssssssssssssssss
ss
s
s
ssssssssssss

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)