Что делает define php

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 Определение констант

 define("CONSTANT", "Hello world."); echo CONSTANT; // outputs "Hello world." echo Constant; // outputs "Constant" and issues a notice. define("GREETING", "Hello you.", true); echo GREETING; // outputs "Hello you." echo Greeting; // outputs "Hello you." // Works as of PHP 7 define('ANIMALS', array( 'dog', 'cat', 'bird' )); echo ANIMALS[1]; // outputs "cat" ?>

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

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

 var_dump(defined('__LINE__')); var_dump(define('__LINE__', 'test')); var_dump(constant('__LINE__')); var_dump(__LINE__); ?>

Выводится приведенный выше пример:

bool(false) bool(true) string(4) "test" int(5)

Источник

Constants

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren’t actually constants). Constants are case-sensitive. By convention, constant identifiers are always uppercase.

Note:

Prior to PHP 8.0.0, constants defined using the define() function may be case-insensitive.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

It is possible to define() constants with reserved or even invalid names, whose value can only be retrieved with the constant() function. However, doing so is not recommended.

Example #1 Valid and invalid constant names

// Valid constant names
define ( «FOO» , «something» );
define ( «FOO2» , «something else» );
define ( «FOO_BAR» , «something more» );

// Invalid constant names
define ( «2FOO» , «something» );

// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define ( «__FOO__» , «something» );

Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 128 through 255 (0x80-0xff).

Like superglobals, the scope of a constant is global. Constants can be accessed from anywhere in a script without regard to scope. For more information on scope, read the manual section on variable scope.

Note: As of PHP 7.1.0, class constant may declare a visibility of protected or private, making them only available in the hierarchical scope of the class in which it is defined.

User Contributed Notes 13 notes

11/14/2016 — note updated by sobak
——

CONSTANTS and PHP Class Definitions

Using «define(‘MY_VAR’, ‘default value’)» INSIDE a class definition does not work as expected. You have to use the PHP keyword ‘const’ and initialize it with a scalar value — boolean, int, float, string (or array in PHP 5.6+) — right away.

define ( ‘MIN_VALUE’ , ‘0.0’ ); // RIGHT — Works OUTSIDE of a class definition.
define ( ‘MAX_VALUE’ , ‘1.0’ ); // RIGHT — Works OUTSIDE of a class definition.

//const MIN_VALUE = 0.0; RIGHT — Works both INSIDE and OUTSIDE of a class definition.
//const MAX_VALUE = 1.0; RIGHT — Works both INSIDE and OUTSIDE of a class definition.

class Constants
<
//define(‘MIN_VALUE’, ‘0.0’); WRONG — Works OUTSIDE of a class definition.
//define(‘MAX_VALUE’, ‘1.0’); WRONG — Works OUTSIDE of a class definition.

const MIN_VALUE = 0.0 ; // RIGHT — Works INSIDE of a class definition.
const MAX_VALUE = 1.0 ; // RIGHT — Works INSIDE of a class definition.

public static function getMinValue ()
<
return self :: MIN_VALUE ;
>

public static function getMaxValue ()
<
return self :: MAX_VALUE ;
>
>

?>

#Example 1:
You can access these constants DIRECTLY like so:
* type the class name exactly.
* type two (2) colons.
* type the const name exactly.

#Example 2:
Because our class definition provides two (2) static functions, you can also access them like so:
* type the class name exactly.
* type two (2) colons.
* type the function name exactly (with the parentheses).

#Example 1:
$min = Constants :: MIN_VALUE ;
$max = Constants :: MAX_VALUE ;

#Example 2:
$min = Constants :: getMinValue ();
$max = Constants :: getMaxValue ();

?>

Once class constants are declared AND initialized, they cannot be set to different values — that is why there are no setMinValue() and setMaxValue() functions in the class definition — which means they are READ-ONLY and STATIC (shared by all instances of the class).

Lets expand comment of ‘storm’ about usage of undefined constants. His claim that ‘An undefined constant evaluates as true. ‘ is wrong and right at same time. As said further in documentation ‘ If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string. ‘. So yeah, undefined global constant when accessed directly will be resolved as string equal to name of sought constant (as thought PHP supposes that programmer had forgot apostrophes and autofixes it) and non-zero non-empty string converts to True.

There are two ways to prevent this:
1. always use function constant(‘CONST_NAME’) to get constant value (BTW it also works for class constants — constant(‘CLASS_NAME::CONST_NAME’) );
2. use only class constants (that are defined inside of class using keyword const) because they are not converted to string when not found but throw exception instead (Fatal error: Undefined class constant).

Warning, constants used within the heredoc syntax (http://www.php.net/manual/en/language.types.string.php) are not interpreted!

Editor’s Note: This is true. PHP has no way of recognizing the constant from any other string of characters within the heredoc block.

The documentation says, «You can access constants anywhere in your script without regard to scope», but it’s worth keeping in mind that a const declaration must appear in the source file before the place where it’s used.

This doesn’t work (using PHP 5.4):
foo ();
const X = 1 ;
function foo () echo «Value of X: » . X ;
>
?>
Result: «Value of X: X»

But this works:
const X = 1 ;
foo ();
function foo () echo «Value of X: » . X ;
>
?>
Result: «Value of X: 1»

This is potentially confusing because you can refer to a function that occurs later in your source file, but not a constant. Even though the const declaration is processed at compile time, it behaves a bit like it’s being processed at run time.

I find using the concatenation operator helps disambiguate value assignments with constants. For example, setting constants in a global configuration file:

define ( ‘LOCATOR’ , «/locator» );
define ( ‘CLASSES’ , LOCATOR . «/code/classes» );
define ( ‘FUNCTIONS’ , LOCATOR . «/code/functions» );
define ( ‘USERDIR’ , LOCATOR . «/user» );
?>

Later, I can use the same convention when invoking a constant’s value for static constructs such as require() calls:

require_once( FUNCTIONS . «/database.fnc» );
require_once( FUNCTIONS . «/randchar.fnc» );
?>

as well as dynamic constructs, typical of value assignment to variables:

$userid = randchar ( 8 , ‘anc’ , ‘u’ );
$usermap = USERDIR . «/» . $userid . «.png» ;
?>

The above convention works for me, and helps produce self-documenting code.

If you are looking for predefined constants like
* PHP_OS (to show the operating system, PHP was compiled for; php_uname(‘s’) might be more suitable),
* DIRECTORY_SEPARATOR («\\» on Win, ‘/’ Linux. )
* PATH_SEPARATOR (‘;’ on Win, ‘:’ on Linux. )
they are buried in ‘Predefined Constants’ under ‘List of Reserved Words’ in the appendix:
http://www.php.net/manual/en/reserved.constants.php
while the latter two are also mentioned in ‘Directory Functions’
http://www.php.net/manual/en/ref.dir.php

PHP Modules also define constants. Make sure to avoid constant name collisions. There are two ways to do this that I can think of.
First: in your code make sure that the constant name is not already used. ex. ?> This can get messy when you start thinking about collision handling, and the implications of this.
Second: Use some off prepend to all your constant names without exception ex.

Perhaps the developers or documentation maintainers could recommend a good prepend and ask module writers to avoid that prepend in modules.

class constant are by default public in nature but they cannot be assigned visibility factor and in turn gives syntax error

const MAX_VALUE = 10 ;
public const MIN_VALUE = 1 ;

// This will work
echo constants :: MAX_VALUE ;

// This will return syntax error
echo constants :: MIN_VALUE ;
?>

Источник

Что делает define php

Задумывались ли вы кода-нибудь — смотришь на синтаксис и видишь фигу. (интерпретация «смотришь в книгу видишь фигу»)

Для этого и существует наш сайт, чтобы эти фиги не вылазили!

На не раскрашенные строки, можно даже не смотреть!

case_insensitive — зависимость от регистра.

Как работает define();

Имя константы задаётся параметром name;

Значение константы определяется параметром value.

Если case_insensitive используется как TRUE, то регистр отключен.

Примеры использования define/константы в php

Давайте разберем пример использования и вывода константы:

Выведем ранее заданную константу через echo:

Результат вывода значения константы:

Далее. попробуем изменить значение константы:

Выведем тут же через echo:

Как видим, значение нашей константы не изменилось, что собственно мы и хотели показать!

Ошибки констант в php

Notice: Constant already defined

Если при таком алгоритме создании константы, то выведет ошибку «Notice: Constant already defined»(если вывод данной ошибки включен) и результат echo «val».

define(‘FOO’, ‘val2’); // Notice: Constant already defined

Невозможно задать массив в константе

Невозможно задать массив в константе до PHP 7.0 — возникнет ошибка типа «Warning»

define( ‘FOO’, array(1) ); // Warning: Constants may only evaluate to scalar values in page.html on line №

Источник

PHP define() Function

Constants are much like variables, except for the following differences:

  • A constant’s value cannot be changed after it is set
  • Constant names do not need a leading dollar sign ($)
  • Constants can be accessed regardless of scope
  • Constant values can only be strings and numbers

Syntax

Parameter Values

Technical Details

Return Value: Returns TRUE on success or FALSE on failure
PHP Version: 4+
Changelog: PHP 7.3: Defining case-insensitive constants is deprecated.
PHP 7: The value parameter can also be an array.
PHP 5: The value parameter must be a string, integer, float, boolean or NULL.

❮ PHP Misc Reference

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Loaded java lang unsupportedclassversionerror
Оцените статью