PHP.mk документација

constant

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.constant.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.constant.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
constant

Референца за `function.constant.php` со подобрена типографија и навигација.

function.constant.php

constant

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

constantВраќа вредност на константа

= NULL

constant(string $name): mixed

Вратете ја вредноста на константата означена со name.

constant() е корисно ако треба да ја добиете вредноста на константа, но не го знаете нејзиното име. Односно, таа е зачувана во променлива или вратена од функција.

Оваа функција работи и со константи во класа and случаи на enum.

Параметри

name

Име на константа.

Вратени вредности

Враќа вредност на константата.

Errors/Exceptions

Ако константата не е дефинирана, се фрла Грешка исклучок. Пред PHP 8.0.0, во тој случај се генерираше грешка од E_WARNING ниво.

Дневник на промени

Верзија = NULL
8.0.0 Ако константата не е дефинирана, constant() сега фрла Грешка исклучок; претходно се генерираше E_WARNING и null .

Примери

Пример #1 Користење constant() со Константи

<?php

define
("MAXSIZE", 100);

echo
MAXSIZE;
echo
constant("MAXSIZE"); // same thing as the previous line


interface bar {
const
test = 'foobar!';
}

class
foo {
const
test = 'foobar!';
}

$const = 'test';

var_dump(constant('bar::'. $const)); // string(7) "foobar!"
var_dump(constant('foo::'. $const)); // string(7) "foobar!"

?>

Пример #2 Користење constant() со Enum случаи (од PHP 8.1.0)

<?php

enum Suit
{
case
Hearts;
case
Diamonds;
case
Clubs;
case
Spades;
}

$case = 'Hearts';

var_dump(constant('Suit::'. $case)); // enum(Suit::Hearts)

?>

Види Исто така

  • define() - Дефинира именувана константа
  • defined() - отстрани дадена променлива
  • get_defined_constants() - Враќа асоцијативна низа со имињата на сите константи и нивните вредности
  • HTTP автентикација Константи

Белешки од корисници 16 белешки

Јоаким Крујсвајк
21 години пред
The constant name can be an empty string.

Code:

define("", "foo");
echo constant("");

Output:

foo
т точка kmieliauskas на gmail точка com
пред 10 години
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:

<?php
class Foo {
    const BAR = 42;
}
?>
<?php
namespace Baz;
use \Foo as F;

echo constant(F::class.'::BAR');
?>

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)
Ричард Џ. Тарнер
пред 13 години
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:

<?php
class Foo {
    const BAR = 42;
}
?>

<?php
namespace Baz;

use \Foo as F;

echo constant('F::BAR');
?>

However, calling constant('Foo::BAR') will work as expected.
helvete на zhouba точка cz
пред 9 години
It is worth noting, that keyword 'self' can be used for constant retrieval from within the class it is defined

<?php
class Foo {
  const PARAM_BAR = 'baz';

  public function getConst($name) {
    return constant("self::{$name}");
  }
}

$foo = new Foo();
echo $foo->getConst('PARAM_BAR'); // prints 'baz'
?>
Тревор Блекберд > yurab.com
19 години пред
Technically you can define constants with names that are not valid for variables:

<?php

// $3some is not a valid variable name
// This will not work
$3some = 'invalid';

// This works
define('3some', 'valid');
echo constant('3some');

?>

Of course this is not a good practice, but PHP has got you covered.
XC
19 години пред
When you often write lines like

<?php

if(defined('FOO') && constant('FOO') === 'bar')
{
...
}

?>

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

<?php

function getconst($const)
{
    return (defined($const)) ? constant($const) : null;
}

?>

Finally you can check the value with

<?php

if(getconst('FOO') === 'bar')
{
...
}

?>

It's simply shorter.
Андре
пред 22 години
Maybe this is useful:

$file_ext is the file Extension of the image

<?php
if ( imagetypes() & @constant('IMG_' . strtoupper($file_ext)) )
{
    $file_ext = $file_ext == 'jpg' ? 'jpeg' : $file_ext;
    $create_func = 'ImageCreateFrom' . $file_ext;
}
?>
hellekin
пред 15 години
Checking if a constant is empty is bork... 

You cannot

<?php
define('A', '');
define('B', 'B');

if (empty(B)) // syntax error
if (empty(constant('B'))) // fatal error

// so instead, thanks to LawnGnome on IRC, you can cast the constants to boolean (empty string is false)
if (((boolean) A) && ((boolean) B)) 
  // do stuff
?>
narada точка sage на googlemail точка com
19 години пред
To access the value of a class constant use the following technique.

<?php

class a {
    const b = 'c';
}

echo constant('a::b');

// output: c

?>
Анонимен
20 години пред
In reply to VGR_experts_exchange at edainworks dot com

To check if a constant is boolean, use this instead:

<?php
if (TRACE === true)  {}
?>

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.
nikolays93 на ya точка ru
пред 5 години
<?php

namespace Foo;

define(__NAMESPACE__ . '\Bar', 'its work'); // ..but IDE may make notice

echo Bar; // its work
bohwaz
пред 15 години
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.

<?php

function findConstantsFromObject($object, $filter = null, $find_value = null)
{
    $reflect = new ReflectionClass($object);
    $constants = $reflect->getConstants();
    
    foreach ($constants as $name => $value)
    {
        if (!is_null($filter) && !preg_match($filter, $name))
        {
            unset($constants[$name]);
            continue;
        }
        
        if (!is_null($find_value) && $value != $find_value)
        {
            unset($constants[$name]);
            continue;
        }
    }
    
    return $constants;
}

?>

Examples :

<?php

class Example
{
    const GENDER_UNKNOW = 0;
    const GENDER_FEMALE = 1;
    const GENDER_MALE = 2;

    const USER_OFFLINE = false;
    const USER_ONLINE = true;
}

$all = findConstantsFromObject('Example');

$genders = findConstantsFromObject('Example', '/^GENDER_/');

$my_gender = 1;
$gender_name = findConstantsFromObject('Example', '/^GENDER_/', $my_gender);

if (isset($gender_name[0]))
{
    $gender_name = str_replace('GENDER_', '', key($gender_name));
}
else
{
    $gender_name = 'WTF!';
}

?>
адам на adamhahn точка com
пред 14 години
This function is namespace sensitive when calling class constants.

Using:
<?php namespace sub;

class foo {
    const BAR = 'Hello World';
}

constant('foo::BAR'); // Error

constant('sub\foo::BAR'); // works

?>

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.
Анонимен
пред 6 години
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,

    <?php if(BOO) do_something(); ?>

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:  
     <?php if (constant(BOO)) do_something() ?>  

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,   
<?php if (IS_SPECIAL_CASE) show_php_info() ?> .  

There are other ways around this PHP behavior, such as   
<?php if (BOO === true) do_something(); ?>  
or  
<?php if (defined('BOO') && BOO) do_something() ?>.   

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)
dachnik
пред 15 години
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
мохамед алзокаили
пред 8 години
// 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$
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.