Define php что это

от admin

define

Определяет именованную константу во время выполнения.

Parameters

Note:

Можно определить константы () с зарезервированными или даже недопустимыми именами, значение которых можно (только) получить с помощью constant () . Однако делать это не рекомендуется.

Значение константы. В PHP 5 value должно быть скалярным значением (int, float, string, bool или null ). В PHP 7 также принимаются значения массива.

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

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

Определение констант без учета регистра устарело, начиная с PHP 7.3.0. Начиная с PHP 8.0.0 допустимо только значение false , передача значения true приведет к появлению предупреждения.

Note:

Нечувствительные к регистру константы хранятся в нижнем регистре.

Return Values

Возвращает true в случае успеха или false в случае неудачи.

Changelog

Version Description
8.0.0 Передача true в case_insensitive теперь выдает E_WARNING . Передача false по-прежнему разрешена.
7.3.0 case_insensitive устарел и будет удален в версии 8.0.0.
7.0.0 допускаются значения массива.

Examples

Пример # 1 Определение констант

Пример # 2 Константы с зарезервированными именами

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

Define php что это

The define() function is basically used by programmers to create constant. Constants in PHP are very similar to variables and the only difference between both are the values of constants can not be changed once it is set in a program.

define() returns a Boolean value. It will return TRUE on success and FALSE on failure of the expression.

Syntax:

Parameters:

  • $constant: It is of String type that describes the name of the constant and is a required parameter.
  • $value: It is of mixed type and it describes the Value of the constant and is required in parameter
  • $case_insensitive: It is of a boolean type that describes whether the name of the constant can be case-sensitive or not and it is an optional parameter.

Return Value: This method returns a boolean value TRUE on success and FALSE on the failure of the expression.

Example 1: In this example, we have created a constant namely GREETINGS and its value is Hello GFG and the name of the constant is case-insensitive by using define() function.

How to use Constants in PHP

In this tutorial, we will be showing you how you can define and use constants in PHP.

In PHP, a constant is an identifier that holds a specified value. The value stored within a constant can only be defined at runtime.

You can’t change the value stored within a constant after it has been defined. It is helpful for values you want to access throughout your PHP script and don’t want or need their value to be changed.

For example, you can use a constant within PHP to store your SQL server’s login details for access during runtime.

There are two ways that you can define a constant within PHP.

  • The first method is to utilize the define() function. These constants are handled during runtime.
  • The second method is to use the “ const ” keyword. Constants defined using this are set during compile time before your code is ran.

We will explore these methods and explain some fundamental differences between them within this guide.

When naming a constant within your PHP code, you should always use uppercase letters. Additionally, a constant still follows standard variable naming rules.

A constant must start with a letter or underscore, followed by letters, numbers, or underscores. However, it would help to avoid writing constants that start with and end with two underscores. PHP’s “magic constants” typically use these.

When referencing a constant within your code, you do not use the dollar sign ( $ ) before its name. So, for example, you would use “ FTP_DETAILS ” and not “ $FTP_DETAILS “.

Lastly, by default, constants are automatically accessible throughout your entire script, which means that PHP can access them throughout your code.

Defining Constants using PHP’s define() Function

The define() function is one of the two ways to define a variable as being a constant within the PHP language. It is not as user-readable as the “ const ” keyword but still has some advantages.

When constants are defined using this function, they are not processed until run time. Meaning you can use PHP’s conditional statements to dictate whether the constant is defined or not.

The syntax for using the define function is straightforward, with it only having two parameters that you need to worry about.

The first parameter ( NAME ) is where you will set the name for your constant.

Remember that when setting the name here, you should use uppercase letters. So, for example, a valid name for a constant in PHP would be “ FTP_DETAILS “.

The second ( VALUE ) parameter is where you will set the value you want to be assigned to your constant.

Basic Declaration of a Constant in PHP using define()

Let us show you how simple it is to use the define() function to declare a constant within PHP.

We will use the name “ WEBSITE ” for this constant and set the value to a string containing “ pimylifeup.com “.

You can see that when we used the define function, we passed our variable name into the first parameter, then the value we wanted to set to the second parameter.

We then utilize PHP’s inbuilt echo function to output the value that we set our constant.

Remember that you must avoid using the dollar sign ( $ ) in front of its name to utilize a constant. A constant is referenced purely using its name. So for example, you would use “ CONSTANT “, instead of “ $CONSTANT “.

Constants Declared with define() are Global

Constants that are declared using the define() function become globally available to the current PHP script. You can even use it within functions and classes.

To showcase this, let us write a simple script. This script will contain a function called foo() that will output the value of our constant when called.

With this example, you can see how the constant can be still utilized within a function.

Likewise, if we were to write a simple class called Bar, you can see how you can still use a PHP constant within it.

We will use the same “ define() ” function as our previous example. This time we will make a simple class called “ Bar “. In this classes construction method, we will echo the value of the “ WEBSITE ” constant.

Declaring Constants in PHP within a Different Namespace

Declaring a constant when using the define function using a different namespace isn’t the clearest code. By default, the define function will also default to the global namespace.

When declaring a constant within a particular namespace, you need to include the namespace as part of its name.

For example, if you want the constant to be a part of a namespace called “ pimylifeup ” you would use “ pimylifeup\NAME “.

The example below shows you how to declare a constant using the define function under a specific namespace.

We then print the constant we created under the current namespace.

Unless needed, you should use the “ const ” keyword. It will automatically be declared under the current namespace.

Conditionally Declaring Constants in PHP using the Define() Function

The key advantage of using the define() function over the “const” keyword to declare a constant is when they are processed.

A constant isn’t processed until runtime using the define() function, meaning it can be conditionally set.

Conversely, constants defined using the “ const ” keyword are processed at compile time. Meaning they are defined before any code runs.

With the following example, we use the “ defined() ” function to see if the constant has already been defined. If it hasn’t, we declare it.

This snippet is useful if the constant could of possibly been defined elsewhere in the code.

You can Pass Arrays into the define() Function

Starting with PHP 7, it is possible to use an array as the value of a constant when using the define function.

Before the release of 7.0, you would be required to use the const keyword whenever you wanted to define an array as a constant.

All you need to do is set the value to an array. We will be writing a simple example, declaring the “ FOOD ” constant with a simple array.

You access elements of a constant array just like you would with a normal array within PHP. With the example below, we will print out the third element of the array.

Using the const Keyword in PHP to define a Constant

The second way of declaring a constant in PHP is to use the const keyword. This is considered more readable than using the “ define() ” function and has some behavioral differences.

When using the const keyword, a constant is set during compilation time, not run time. Unfortunately, this means you cannot use the const keyword within conditional statements.

Like using the define() function, you should write the constant name in uppercase letters or numbers.

The basic syntax for using the const keyword to define a constant in PHP is as we have shown it below.

Basic Usage of the const Keyword to Declare Constants

For this example, we will declare a new constant using PHP’s const keyword. We will name this constant “ WEBSITE ” and assign it the value “ pimylifeup.com “.

Once declared, we will use the echo function to print the value of the constant to the screen.

Using const to Declare Global Constants in PHP

You can use the const keyword to declare constants globally in PHP. All you need to do is ensure that it is declared outside of a namespace or class.

With the example below, you can see that our “ WEBSITE ” constant is still accessible from within the “ bar() ” function.

When the function is called, it will print the value of our global constant.

You can Declare Constants within a PHP Class using the const Keyword

Unlike the define function, you can use the const keyword to declare a constant within a class.

Unless you specify it differently, the constant will be publicly accessible.

With this example, we will show you various ways to declare and access a constant within a class in PHP.

When you declare your constant within the class, you can access it by using “ self:: ” followed by the constant name.

Outside of the class you can reference the constant by accessing the class statically (E.G. “ foo:: “) or by creating a function that outputs the value of the constant.

Constants Declared with the const Keyword Adopt the Current Namespace

Constants that are declared within PHP using the const keyword will adopt the currently set namespace.

This is much cleaner to use than the define function, where you must include the namespace in its declaration.

The example below will show you how easy it is to declare a constant within a namespace using the const keyword. We then print the declared value.

Conclusion

Throughout this guide, we have shown you the various ways to declare a constant in PHP.

A constant is a variable that’s value doesn’t and cannot be changed after its initial declaration. PHP’s “ define() ” function allows you to declare constants that are created during runtime.

The inbuilt const keyword allows you to declare constants that are created at compilation time. There is a small performance boost by using this over the define function.

Please comment below if you have any questions about dealing with constants in PHP.

To learn more about PHP and its various features, check out our many other PHP guides. We also have tutorials that cover other programming languages as well.

define

Определяет именованную константу во время выполнения.

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

Замечание:

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

Значение константы. В PHP 5 value должно быть скалярным значением ( int , float , string , bool или null ). В PHP 7 также возможно использовать тип array .

Хотя возможно определить константы с типом resource , не рекомендуется это делать, поскольку может привести к непредсказуемому поведению.

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

Начиная с PHP 7.3.0, определение нечувствительных к регистру констант объявлено устаревшим. Начиная с PHP 8.0.0, допустимым значением является только false , передача true вызовет предупреждение.

Замечание:

Нечувствительные к регистру константы хранятся в нижнем регистре.

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

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

Список изменений

Версия Описание
8.0.0 Передача true в case_insensitive теперь выдаёт ошибку уровня E_WARNING . Передача false всё ещё разрешена.
7.3.0 Параметр case_insensitive объявлен устаревшим и будет удалён в версии 8.0.0.
7.0.0 Допустимы значения типа array .

Примеры

Пример #1 Определение констант

<?php
define ( «CONSTANT» , «Hello world.» );
echo CONSTANT ; // выводит «Hello world.»
echo Constant ; // выводит «Constant» и выдаёт уведомление.

define ( «GREETING» , «Hello you.» , true );
echo GREETING ; // выводит «Hello you.»
echo Greeting ; // выводит «Hello you.»

// Начиная с PHP 7
define ( ‘ANIMALS’ , array(
‘собака’ ,
‘кошка’ ,
‘птица’
));
echo ANIMALS [ 1 ]; // выводит «кошка»

Пример #2 Определение констант зарезервированными именами

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

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

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

  • defined() — Проверяет существование указанной именованной константы
  • constant() — Возвращает значение константы
  • Смотрите раздел Константы

User Contributed Notes 16 notes

Be aware that if «Notice»-level error reporting is turned off, then trying to use a constant as a variable will result in it being interpreted as a string, if it has not been defined.

I was working on a program which included a config file which contained:

<?php
define ( ‘ENABLE_UPLOADS’ , true );
?>

Since I wanted to remove the ability for uploads, I changed the file to read:

<?php
//define(‘ENABLE_UPLOADS’, true);
?>

However, to my surprise, the program was still allowing uploads. Digging deeper into the code, I discovered this:

<?php
if ( ENABLE_UPLOADS ):
?>

Since ‘ENABLE_UPLOADS’ was not defined as a constant, PHP was interpreting its use as a string constant, which of course evaluates as True.

Not sure why the docs omit this, but when attempting to define() a constant that has already been defined, it will fail, trigger an E_NOTICE and the constant’s value will remain as it was originally defined (with the new value ignored).

(Guess that’s why they’re called «constants».)

define() will define constants exactly as specified. So, if you want to define a constant in a namespace, you will need to specify the namespace in your call to define(), even if you’re calling define() from within a namespace. The following examples will make it clear.

The following code will define the constant «MESSAGE» in the global namespace (i.e. «\MESSAGE»).

<?php
namespace test ;
define ( ‘MESSAGE’ , ‘Hello world!’ );
?>

The following code will define two constants in the «test» namespace.

<?php
namespace test ;
define ( ‘test\HELLO’ , ‘Hello world!’ );
define ( __NAMESPACE__ . ‘\GOODBYE’ , ‘Goodbye cruel world!’ );
?>

With php 7 you can now define arrays.

consider the following code:
<?php

define ( «EXPLENATIVES» , [ 1 => «Foo Bar» , 2 => «Fehw Bahr» , 3 => «Foo Bahr» , 4 => «Fooh Bar» , 5 => «Fooh Bhar» , 6 => «Foo Barr» , 7 => «Foogh Bar» , 8 => «Fehw Barr» , 9 => «Fu bar» , 10 => «Foo Bahr» , 11 => «Phoo Bar» , 12 => «Foo Bawr» , 13 => «Phooh Baughr» , 14 => «Foogan Bargan» , 15 => «Foo Bahre» , 16 => «Fu Bahar» , 17 => «Fugh Bar» , 18 => «Phou Baughr» ]);

//set up define methods using mixed values; both array and non-array values
define ( «NAVBTNS» , [ EXPLENATIVES , «Nouns» , «Verbs» , «Adjectives» ]);

//function to create a dropdown menu using the EXPLENATIVES array $btn=EXPLENATIVES=assoc_array

Love this new implementation !

This is obvious, but easy to forget: if you include a file, the include file can only make use of constants already defined. For example:

<?php
define ( «VEG» , «cabbage» );
require( «another file» );
define ( «FRUIT» , «apple» );

// «another file»:
echo VEG ; // cabbage
echo FRUIT ; // FRUIT
?>

The value of a constant can be the value of another constant.

define ( «NEW_GOOD_NAME_CONSTANT» , «I have a value» );
define ( «OLD_BAD_NAME_CONSTANT» , NEW_GOOD_NAME_CONSTANT );

echo NEW_GOOD_NAME_CONSTANT ; // current
echo OLD_BAD_NAME_CONSTANT ; // legacy

Found something interesting. The following define:

<?php
define ( «THIS-IS-A-TEST» , «This is a test» );
echo THIS — IS — A — TEST ;
?>

Will return a ‘0’.

<?php
define ( «THIS_IS_A_TEST» , «This is a test» );
echo THIS_IS_A_TEST ;
?>

Will return ‘This is a test’.

This may be common knowledge but I only found out a few minutes ago.

[EDIT BY danbrown AT php DOT net: The original poster is referring to the hyphens versus underscores. Hyphens do not work in defines or variables, which is expected behavior.]

You can define constants with variable names (works also with constant values or variables or array values or class properties and so on — as long it’s a valid constant name).

# Define a constant and set a valid constant name as string value
define ( «SOME_CONSTANT» , «NEW_CONSTANT» );

# Define a second constant with dynamic name (the value from SOME_CONSTANT)
define ( SOME_CONSTANT , «Some value» );

# Output
echo SOME_CONSTANT ; // prints «NEW_CONSTANT»
echo «<br>» ;
echo NEW_CONSTANT ; // prints «Some value»

?>

Needless to say that you’ll lose your IDE support for refactoring and highlighting completely for such cases.
No clue why someone would / could actually use this but i thought it’s worth mentioning.

There’s an undocumented side-effect of setting the third parameter to true (case-insensitive constants): these constants can actually be «redefined» as case-sensitive, unless it’s all lowercase (which you shouldn’t define anyway).

The fact is that case-sensitive constants are stored as is, while case-insensitive constants are stored in lowercase, internally. You’re still allowed to define other constants with the same name but capitalized differently (except for all lowercase).

<?php
// «echo CONST» prints 1, same as «echo const», «echo CoNst», etc.
define ( ‘CONST’ , 1 , true );
echo CONST; // Prints 1

define ( ‘CONST’ , 2 );
echo CONST; // Prints 2
echo CoNsT; // Prints 1
echo const; // Prints 1

// ** PHP NOTICE: Constant const already defined **
define ( ‘const’ , 3 );
echo const; // Prints 1
echo CONST; // Prints 2
?>

Why would you use this?

A third party plugin might attempt to define a constant for which you already set a value. If it’s fine for them to set the new value, assuming you cannot edit the plugin, you could define your constant case-insensitive. You can still access the original value, if needed, by using any capitalization other than the one the plugin uses. As a matter of fact, I can’t think of another case where you would want a case-insensitive constant.

Php 7 — Define: «Defines a named constant at runtime. In PHP 7, array values are also accepted.»

But prior PHP 7, you can maybe do this, to pass an array elsewhere using define:

$to_define_array = serialize($array);
define( «DEFINEANARRAY», $to_define_array );

$serialized = DEFINEANARRAY; // passing directly the defined will not work
$our_array = unserialize($serialized);

I think worth mentioning is that define() appears to ignore invalid constant names.
One immediate implication of this seem to be that if you use an invalid constant name you have to use constant() to access it and obviously that you can’t use the return value from define() to tell you whether the constant name used is invalid or not.

For example:
$name = ‘7(/!§%’;
var_dump(define($name, «hello»)); // outputs bool(true)
var_dump(constant($name)); // outputs string(5) «hello»

To clear up a few thing:
Integers with 0 in front work. But since PHP (and many other languages) handle them as octal values, they’re only allowed a range of 0-7:

<?php
define ( ‘GOOD_OCTAL’ , 0700 );
define ( ‘BAD_OCTAL’ , 0800);

print GOOD_OCTAL ;
print ‘<br>’ ;
print BAD_OCTAL ;
?>

Result:
448
0

writing the constant name without the quotation-marks (as mentioned in the notes) throws an E_NOTICE and should be avoided!

<?php
define ( TEST , ‘Throws an E_NOTICE’ );
?>

Result:
Notice: Use of undefined constant TEST — assumed ‘TEST’

For translating with variables and define, take also a look on the constant() function.

<?php
define ( ‘PAYMENT_IDEAL’ , «iDEAL Payment ( NL only )» );
define ( ‘PAYMENT_MASTERCARD’ , «Mastercard Payment ( international )» );

echo constant ( «PAYMENT_ $payparam » );

// output :
// Mastercard Payment ( international )
?>

It may be worth stating that a define function must be executed before its global constant is referenced.

Abc();
define(«TEST», 23);
function Abc()
<
echo TEST;
> // Abc

This code fails with a Notice-level message. TEST is treated here as being the string «TEST».

If you happen to name your constant the same as a function name (either a built-in function or a user-defined one), PHP can handle this correctly based on context. For example:

<?php
function myfunc () <
return ‘function output’ ;
>

define ( ‘MYFUNC’ , ‘constant value’ );

// note that function names are NOT case-sensitive
// so calling MYFUNC() is the same as calling myfunc()

echo ‘MYFUNC(): ‘ . MYFUNC () . ‘, MYFUNC: ‘ . MYFUNC ;
?>

Output:
MYFUNC(): function output, MYFUNC: constant value

A namespace constant can be defined using the define function, the constant defined this way is not global.

<?php
namespace WuXiancheng ;
\ define ( ‘China\Sichuan\Guangan\Yuechi\ZIP’ , 638300 );
echo ZIP ; //Use of undefined constant ZIP
echo \ China \ Sichuan \ Guangan \ Yuechi \ ZIP ; // 638300
?>

Читать:
Как запустить dirt 3 на windows 10

Похожие статьи