Php проверить наличие константы

How to tell if a PHP constant has been defined already

You can define constants in PHP with the define() function and can check if a constant has already been defined with the defined() function. This post looks at both functions with some examples.

Defining a constant with PHP

Before showing some examples of checking if a constant has been defined with PHP we’ll briefly look at how to define a constant first. This is done with the define() function where the first parameter passed is the name of the constant and the second parameter the value.

The following example sets the constant FOO with the value ‘bar’. Constant names do not have to be uppercase but the naming convention means they usually are:

Note the constant name is enclosed with quotes. Without the quotes you are actually passing a constant to the function instead of the name, and will generate a notice type error mesage if that constant has not already been defined like so:

PHP Notice: Use of undefined constant FOO - assumed 'FOO' in .

If the constant FOO has not already been defined then it will actually define a constant with the name FOO anyway; this is undesirable behaviour and may have unexpected consequences depending if the constant had already been defined or not, so make sure you always use either single quotes or double quotes when defining the name of the constant.

Notice error if a constant is defined twice

If you attempt to define a constant twice in PHP you will get a notice type error message. The following example attempts to define FOO twice:

define('FOO', 'bar'); define('FOO', 'bar');

And you will get an error message like so:

PHP Notice: Constant FOO already defined in .

Checking to see if a constant has been defined with PHP

Checking to see if a function has already been defined in PHP is done using the defined() function which works in a similar way to the define() function. A single parameter is passed in which again needs to be a single or double quoted string.

To test if FOO has been defined and to take appropriate action, you could do something like this:

To do something only if FOO hasn’t been defined you could do this:

Читайте также:  Html xml xhtml html5

And finally, to test to see if the constant FOO has been defined and define it if it hasn’t, do this:

Future posts

In next Monday’s post I’ll look at how to specify a custom error handler for the PHP ADODB Lite database abstraction library. This involves the use of defining appropriate constants and so is a good follow up to this post with a real world example.

Make sure you subscribe to my RSS feed (details below) if you haven’t already so you keep up to date with posts on my blog as they are made.

Источник

Php проверить наличие константы

Константы, как и переменные хранят определенное значение, только в отличие от переменных значение констант может быть установлено только один раз, и далее мы уже не можем его изменить. Константы обычно определяются для хранения значений, которые должны оставаться неизменными на протяжении всей работы скрипта.

Оператор const

Для определения константы применяется оператор const , при этом в названии константы знак доллара $ (в отличие от переменных) не используется.

Обычно названия констант используют заглавные символы, но это условность.

После определения константы мы можем ее использовать также, как и обычную переменную.

PHP позволяет устанавливать значения констант на основе вычисляемых выражений:

Единственное исключение — мы не сможем изменить значение константы. То есть выражение PI = 3.1415; , которое должно изменить значение константы, не срабатает.

Функция define

Также для определения константы может применяться функция define() , которая имеет следующую форму:

define(string $name, string $value)

Параметр $name передает название константы, а параметр $value — ее значение. Значение константы может представлять тип int, float, string, bool, null или массивы.

Например, определим числовую константу:

Магические константы

Кроме создаваемых программистом констант в PHP имеется еще несколько так называемых «магических» констант, которые есть в языке по умолчанию:

  • __FILE__ : хранит полный путь и имя текущего файла
  • __LINE__ : хранит текущий номер строки, которую обрабатывает интерпретатор
  • __DIR__ : хранит каталог текущего файла
  • __FUNCTION__ : название обрабатываемой функции
  • __CLASS__ : название текущего класса
  • __TRAIT__ : название текущего трейта
  • __METHOD__ : название обрабатываемого метода
  • __NAMESPACE__ : название текущего пространства имен
  • ::class/span>: полное название текущего класса

Например, выведем текущую выполняемую строку и название файла:

Проверка существования константы

Чтобы проверить, определена ли константы, мы можем использовать функцию bool defined(string $name) . Если константа $name определена, то функция будет возвращать значение true

Источник

defined

Проверяет существование и наличие значения указанной константы.

Замечание:

Если необходимо узнать о существовании переменной, то используйте isset() , так как defined() применима лишь для констант. Если вам необходимо узнать о существовании функции, то используйте function_exists() .

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

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

Возвращает true , если именованная константа, указанная в параметре constant_name , была определена, false в противном случае.

Примеры

Пример #1 Проверка констант

/* Важно учесть необходимость использования кавычек. Данный пример проверяет,
* является ли строка ‘TEST’ именем константы TEST. */
if ( defined ( ‘TEST’ )) echo TEST ;
>

Читайте также:  Getter and setter java это

interface bar const test = ‘foobar!’ ;
>

class foo const test = ‘foobar!’ ;
>

var_dump ( defined ( ‘bar::test’ )); // bool(true)
var_dump ( defined ( ‘foo::test’ )); // bool(true)

Пример #2 Проверка вариантов перечисления (начиная с PHP 8.1.0)

enum Suit
case Hearts ;
case Diamonds ;
case Clubs ;
case Spades ;
>

var_dump ( defined ( ‘Suit::Hearts’ )); // bool(true)

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

  • define() — Определяет именованную константу
  • constant() — Возвращает значение константы
  • get_defined_constants() — Возвращает ассоциативный массив с именами всех констант и их значений
  • function_exists() — Возвращает true, если указанная функция определена
  • Смотрите раздел Константы

User Contributed Notes 16 notes

My preferred way of checking if a constant is set, and if it isn’t — setting it (could be used to set defaults in a file, where the user has already had the opportunity to set their own values in another.)

defined ( ‘CONSTANT’ ) or define ( ‘CONSTANT’ , ‘SomeDefaultValue’ );

// Checking the existence of a class constant, if the class is referenced by a variable.

class Class_A
const CONST_A = ‘value A’;
>

// When class name is known.
if ( defined( ‘Class_A::CONST_A’ ) )
echo ‘Class_A::CONST_A defined’;

// Using a class name variable. Note the double quotes.
$class_name = Class_A::class;
if ( defined( «$class_name::CONST_A» ) )
echo ‘$class_name::CONST_A defined’;

// Using an instantiated object for a variable class.
$object_A = new $class_name();
if ( defined( get_class($object_A).’::CONST_A’ ) )
echo ‘$object_A::CONST_A defined’;

Before using defined() have a look at the following benchmarks:

true 0.65ms
$true 0.69ms (1)
$config[‘true’] 0.87ms
TRUE_CONST 1.28ms (2)
true 0.65ms
defined(‘TRUE_CONST’) 2.06ms (3)
defined(‘UNDEF_CONST’) 12.34ms (4)
isset($config[‘def_key’]) 0.91ms (5)
isset($config[‘undef_key’]) 0.79ms
isset($empty_hash[$good_key]) 0.78ms
isset($small_hash[$good_key]) 0.86ms
isset($big_hash[$good_key]) 0.89ms
isset($small_hash[$bad_key]) 0.78ms
isset($big_hash[$bad_key]) 0.80ms

PHP Version 5.2.6, Apache 2.0, Windows XP

Each statement was executed 1000 times and while a 12ms overhead on 1000 calls isn’t going to have the end users tearing their hair out, it does throw up some interesting results when comparing to if(true):

1) if($true) was virtually identical
2) if(TRUE_CONST) was almost twice as slow — I guess that the substitution isn’t done at compile time (I had to double check this one!)
3) defined() is 3 times slower if the constant exists
4) defined() is 19 TIMES SLOWER if the constant doesn’t exist!
5) isset() is remarkably efficient regardless of what you throw at it (great news for anyone implementing array driven event systems — me!)

May want to avoid if(defined(‘DEBUG’)).

You can use the late static command «static::» withing defined as well. This example outputs — as expected — «int (2)»

abstract class class1
<
public function getConst ()
<
return defined ( ‘static::SOME_CONST’ ) ? static:: SOME_CONST : false ;
>
>

final class class2 extends class1
<
const SOME_CONST = 2 ;
>

var_dump ( $class2 -> getConst ());
?>

Источник

How to tell if a PHP constant has been defined already

You can define constants in PHP with the define() function and can check if a constant has already been defined with the defined() function. This post looks at both functions with some examples.

Читайте также:  Php regex search array

Defining a constant with PHP

Before showing some examples of checking if a constant has been defined with PHP we’ll briefly look at how to define a constant first. This is done with the define() function where the first parameter passed is the name of the constant and the second parameter the value.

The following example sets the constant FOO with the value ‘bar’. Constant names do not have to be uppercase but the naming convention means they usually are:

Note the constant name is enclosed with quotes. Without the quotes you are actually passing a constant to the function instead of the name, and will generate a notice type error mesage if that constant has not already been defined like so:

PHP Notice: Use of undefined constant FOO - assumed 'FOO' in .

If the constant FOO has not already been defined then it will actually define a constant with the name FOO anyway; this is undesirable behaviour and may have unexpected consequences depending if the constant had already been defined or not, so make sure you always use either single quotes or double quotes when defining the name of the constant.

Notice error if a constant is defined twice

If you attempt to define a constant twice in PHP you will get a notice type error message. The following example attempts to define FOO twice:

define('FOO', 'bar'); define('FOO', 'bar');

And you will get an error message like so:

PHP Notice: Constant FOO already defined in .

Checking to see if a constant has been defined with PHP

Checking to see if a function has already been defined in PHP is done using the defined() function which works in a similar way to the define() function. A single parameter is passed in which again needs to be a single or double quoted string.

To test if FOO has been defined and to take appropriate action, you could do something like this:

To do something only if FOO hasn’t been defined you could do this:

And finally, to test to see if the constant FOO has been defined and define it if it hasn’t, do this:

Future posts

In next Monday’s post I’ll look at how to specify a custom error handler for the PHP ADODB Lite database abstraction library. This involves the use of defining appropriate constants and so is a good follow up to this post with a real world example.

Make sure you subscribe to my RSS feed (details below) if you haven’t already so you keep up to date with posts on my blog as they are made.

Источник

Оцените статью