PHP Velho Oeste 2024

apc_define_constants

(PECL apc >= 3.0.0)

apc_define_constantsОпределить набор констант для извлечения и массового определения

Описание

apc_define_constants ( string $key , array $constants [, bool $case_sensitive = TRUE ] ) : bool

Общеизвестно, что функция define() медленная. Так как основным преимуществом APC является повышение производительности скриптов и приложений, предусмотрен механизм для упорядочения процесса массового определения констант. Тем не менее, эта функция не так работает хорошо, как ожидалось.

Для более эффективного решения, попробуйте расширение » hidef из PECL.

Замечание: Для удаления набора сохраненных констант (без полной очистки кеша), можно передать в параметр constants пустой массив. Это эффективно удалит сохраненные значения.

Список параметров

key

Параметр key задает имя набору сохраняемых констант. Этот же key используется для извлечения констант функцией apc_load_constants().

constants

Ассоциативный массив пар constant_name => value. constant_name должен следовать правилам именования нормальных констант. value должно приводиться к скалярному значению.

case_sensitive

По умолчанию имена констант регистрозависимы. То есть CONSTANT и Constant являются разными значениями. Если этот параметр равен FALSE константы будут объявлены как нечувствительные к регистру.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования apc_define_constants()

<?php
$constants 
= array(
    
'ONE'   => 1,
    
'TWO'   => 2,
    
'THREE' => 3,
);
apc_define_constants('numbers'$constants);
echo 
ONETWOTHREE;
?>

Результат выполнения данного примера:

123

Смотрите также

add a note add a note

User Contributed Notes 2 notes

up
0
jmucchiello AT yahoooooooo DOT com
13 years ago
It doesn't introduce much overhead if you make use of conditional function definitions:

<?php
if (function_exists('apc_load_constants')) {
    function
define_array($key, $arr, $case_sensitive = true)
    {
        if (!
apc_load_constants($key, $case_sensitive)) {
           
apc_define_constants($key, $arr, $case_sensitive);
        }
    }
} else {
    function
define_array($key, $arr, $case_sensitive = true)
    {
        foreach (
$arr as $name => $value)
           
define($name, $value, $case_sensitive);
    }
}

//in your code you just write something like this:

define_array('NUMBERS', Array('ONE' => 1, 'TWO' => 2, 'THREE' => 3));
?>
up
0
webmaster at thedigitalorchard dot ca
14 years ago
An observation that I've made is that the nature of apc_define_constants() binding the list of constants to a key and then requiring that key to load the constants is limiting. Furthermore, there's no way to append additional constants to a given key.

A solution that I've been adopting is to build a list of constants to be defined, and then do one of two things:

1) if APC is enabled, then use apc_define_constants();
2) ...else loop through the list and define each constant normally.

The problem I've run into is when this process happens at different places in a large application, it can introduce overhead that otherwise wouldn't be there if it was possible to append to an existing list of defined constants in APC.
To Top