CREDIT

Mar 23 2020

Define a credit #Define #a #credit



Define a credit

*******

(PHP 4, PHP 5, PHP 7)

define — Defines a named constant

Description

Defines a named constant at runtime.

Parameters

The name of the constant.

It is possible to define() constants with reserved or even inval >constant() . However, doing so is not recommended.

The value of the constant. In PHP 5, value must be a scalar value ( integer , float , string , boolean , or NULL ). In PHP 7, array values are also accepted.

While it is possible to define resource constants, it is not recommended and may cause unpredictable behavior.

If set to TRUE , the constant will be defined case-insensitive. The default behavior is case-sensitive; i.e. CONSTANT and Constant represent different values.

Defining case-insensitive constants is deprecated as of PHP 7.3.0.

Case-insensitive constants are stored as lower-case.

Return Values

Returns TRUE on success or FALSE on failure.

Version Description
7.3.0 case_insensitive has been deprecated and will be removed in version 8.0.0.
7.0.0 array values are allowed.

Example #1 Defining Constants

( “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”

Example #2 Constants with Reserved Names

This example illustrates the possibility to define a constant with the same name as a magic constant. Since the resulting behavior is obviously confusing, it is not recommended to do this in practise, though.

The above example will output:

  • defined() – Checks whether a given named constant exists
  • constant() – Returns the value of a constant
  • The section on Constants

User Contributed Notes 47 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:

( ‘ENABLE_UPLOADS’ , true );
?>

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

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

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

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.

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 “
” ;
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.

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”).

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

The following code will define two constants in the “test” namespace.

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

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”.)

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

( “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

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”

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:

( “VEG” , “cabbage” );
require( “another file” );
define ( “FRUIT” , “apple” );

// “another file”:
echo VEG ; // cabbage
echo FRUIT ; // FRUIT
?>

Found something interesting. The following define:

( “THIS-IS-A-TEST” , “This is a test” );
echo THIS – IS – A – TEST ;
?>

Will return a ‘0’.

( “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 also define associative array as constant:

( “DB” , [
“DB_HOST_NAME” => “localhost” ,
“DB_USER_NAME” => “root” ,
“DB_PASSWORD” => “password” ,
“DB_DATABASE” => “db_example”
]);

Array ( [ DB_HOST_NAME ] => localhost [ DB_USER_NAME ] => root [ DB_PASSWORD ] => password [ DB_DATABASE ] => db_example )

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);

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

( ‘PAYMENT_IDEAL’ , “iDEAL Payment ( NL only )” );
define ( ‘PAYMENT_MASTERCARD’ , “Mastercard Payment ( international )” );

echo constant ( “PAYMENT_ $payparam ” );

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

In PHP 5 it seems it was possible to redefine predefined constants under certain circumstances. The following code will output 42 in PHP 5:

namespace NS ;
define ( ‘TRUE’ , 42 , false );
echo TRUE ;
?>

In PHP 7 the output is different (1).

With php 7 you can now define arrays.

consider the following code:
( “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 !

define(“THIS+IS_A_TEST”,”This is a test”);
echo THIS+IS_A_TEST;

//It results 0 but with NOTICE ERROR

Rule : Don’t use Operators as constant.

Some people like to have an ambiguous, engine-agnostic database include specified by assigning a single config variable to one of a series of constants. Unfortunately, this can easily become needlessly clunky if these defines are handled in an included config.php file, since more than one hook will throw an ugly “already defined” error.

Here’s a simple way to accomplish this architectural model without having to create a bunch of clumsy sanity checks that compromise scalability:

/* Available databases. –Kris */
$dbengines = array();
$dbengines [] = “mysql” ;
$dbengines [] = “mysqli” ;
$dbengines [] = “pgsql” ;

foreach ( $dbengines as $engine )
<
if ( ! defined ( “_” . strtoupper ( $engine ) . “_” ) )
<
define ( “_” . strtoupper ( $engine ) . “_” , $engine );
>
>

/* Which database engine shall we use? –Kris */
$sql_type = _MYSQLI_ ;

?>
Then, somewhere later in the stack.

/* Include the file with the desired sql class. –Kris */
require_once( $sql_type . “.php” );

/* Now you can use the same code for any supported db engine. –Kris */
$sql = new sql ();
$res = $sql -> query ( . );

Something I found out the “hard” way today: integers starting with 0 won’t work.
( ‘SOMECONSTANT’ , 09900);
var_dump ( SOMECONSTANT );
?>
Produces int(0)

( ‘SOMECONSTANT’ , 9900 );
var_dump ( SOMECONSTANT );
?>
Produces int(9900)

Just like define(), defined() will check for constants exactly as specified. So, if you want to check a constant in a namespace, you will need to specify the namespace in your call to defined(), even if you’re calling defined() from within a namespace.

To check for a defined constant within current namespace, you can use __NAMESPACE__ magic variable:

define ( ‘mytest\CONSTANTINE’ , ‘value’ );

if ( defined ( __NAMESPACE__ . ‘\CONSTANTINE’ )) <
print “Constant is defined and is valued ” . CONSTANTINE ;
>
?>

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:

( ‘GOOD_OCTAL’ , 0700 );
define ( ‘BAD_OCTAL’ , 0800);

print GOOD_OCTAL ;
print ‘
‘ ;
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!

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

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

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).

// “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.

Here is a trick to use constants within the heredoc notation.

( ‘MY_CONSTANT’ , ‘foo bar’ )
$cst = ‘cst’ ;
function cst ( $constant ) <
return $constant ;
>

$string = My constante MY_CONSTANT : < $cst ( MY_CONSTANT )>.
EOF;
echo $string ;
?>

That will echo :

My constante MY_CONSTANT : foo bar .

As you can use function within the heredoc notation the idea is to use a fonction to return the value of the constant.
Be carefull, to use a function, it’s necessary to declare the name of the function as a variable and to use that varaible during the “call” of the constant.

It works for me and doesn’t seem too messy.

Hope that will help.

An improvement on the function from bobbykjack at yahoo dot co dot uk on the concept by richard dot quadling at bandvulc dot co dot uk:
function adefine ( $constant_name , $value = null ) <
static $increment = 0 ; // 1 for bitmask

if ( is_null ( $value )) <
define ( $constant_name , ++ $increment ); // $increment=$increment > else <
define ( $constant_name , $value );
if ( is_numeric ( $value )) <
$increment = $value ;
>
>
>
?>
If you pass it a second argument it defines it normally, and resets the increment if the value is numeric. This way the function can replace define, and you can reset the counter for a new set of constants.
( ‘RULE_CALLBACK_FORMAT’ , 1 ); // 1
adefine ( ‘RULE_CHANGE_CALLBACK_ON_ERROR’ ); // 2
adefine ( ‘RULE_CHANGE_COMPARE_DATE’ ); // 3
adefine ( ‘KEYWORD’ , ‘hodgepodge’ ); // hodgepodge adefine ( ‘RULE_CHANGE_ON_DATE’ ); // 4

adefine ( ‘ERROR_DESC’ , 1 ); // 1 adefine ( ‘ERROR_EXPECTED_RESULT’ ); // 2
?>

In PHP 4.4.9, you cannot use certain names for constants.

Specifically, reserved words such as ‘PRINT’, ‘IF’, etc.

Oddly enough, you get different behaviour for some:

( ‘IF’ , 42 );
echo “IF: ” , IF, ” \n” ;
?>

yields PHP Parse error: syntax error, unexpected T_IF

( ‘PRINT’ , 13 );
echo “PRINT: ” , PRINT, ” \n” ;
?>

yields PHP Parse error: syntax error, unexpected ‘)’

Not sure if this is still true in PHP 5 or not, but it’s worth noting if it is.

With php 5.30 it is possible to make some “restrictions”, in case u use namespaces.
The following function allows only uppercase and, if 3 param isset, gives E_USER_ERROR instead of E_NOTICE:

function define ( $c , $v , $x = false ) <
$c = strtoupper ( $c );
if (! defined ( $c )) <
// not to use \define here, as the syntax highlighting does not work correctly here.
return define ( $c , $v , true );
> else if ( $x == true ) <
trigger_error ( ‘setting constant “‘ . $c . ‘” is not allowed’ , E_USER_ERROR );
>
return null ;
>

define ( ‘PHP_VERSION’ , ‘1’ );
define ( ‘PHP_VERSION’ , ‘1’ ) || trigger_error ( ‘constant already defined’ , E_USER_NOTICE );
define ( ‘PHP_VERSION’ , ‘1’ , true );
?>

A note on redefining:

Constants can’t be redefined:

$ php -r “define(‘A’, 1); var_dump(‘A’); define(‘A’, 2); var_dump(‘A’);”;
string(1) “A”
PHP Notice: Constant A already defined in Command line code on line 1
string(1) “A”

But using the case insensitive setting shows that the internal
representation is lower case:

$ php -r “define(‘A’, 1, true); var_dump(‘A’); define(‘A’, 2); var_dump(‘A’);”;
string(1) “A”
string(1) “A”

Note the lower case ‘a’ in the second define() here:
$ php -r “define(‘A’, 1, true); var_dump(‘A’); define(‘a’, 2); var_dump(‘A’);”;
string(1) “A”
PHP Notice: Constant a already defined in Command line code on line 1
string(1) “A”

This code will define every key of an array, and if its a multidimentional array it will define it as parent_child1_child2_etc.

function define_array ( $array , $keys = NULL )
<
foreach( $array as $key => $value )
<
$keyname = ( $keys ? $keys . “_” : “” ) . $key ;
if( is_array ( $array [ $key ] ) )
define_array ( $array [ $key ], $keyname );
else
define ( $keyname , $value );
>
>
?>

Constants can’t be referenced from within quotes or (more importantly IMHO) from within HEREDOC syntax. This is a huge drawback in my opinion. Here’s two of my workarounds:

//PHP5 only — more efficient
$constarray = get_defined_constants ( true );
foreach( $constarray [ ‘user’ ] as $key => $val )
eval( sprintf ( ‘$_CONSTANTS[\’%s\’] = \’%s\’;’ , addslashes ( $key ), addslashes ( $val )));

//PHP4+ — less efficient because it defines (potentially) hundreds of unnecessary constants
foreach( get_defined_constants () as $key => $val )
eval( sprintf ( ‘$_CONSTANTS[\’%s\’] = \’%s\’;’ , addslashes ( $key ), addslashes ( $val )));

?>

Now you can refer to your defined constants using the $_CONSTANTS array. Note that because this is NOT a superglobal, a few caveats apply:

//run code snippet here to define $_CONSTANTS in global scope.

$mv = $_CONSTANTS [ ‘FOO’ ]; //works

function my_function1 ()
<
$mv = $_CONSTANTS [ ‘BAR’ ]; //doesn’t work! not defined!
>

function my_function2 ()
<
global $_CONSTANTS ;
$mv = $_CONSTANTS [ ‘BAR’ ]; //ah, this works!
>

?>

I realize this is not ideal, either for performance or for convenience of being able to refer to constants without regard to scope, but it is a workaround that works. Depending on your application, it may be easier to shift your paradigm a bit and use the following method instead, declaring your constants as variables first:

//first, define our constants.
$_CONSTANTS [ ‘FOO’ ] = ‘bar’ ;
$_CONSTANTS [ ‘BAR’ ] = ‘foo’ ;

//now, turn them into real constants.
foreach( $_CONSTANTS as $key => $val )
define ( $key , $val );

//now, you can use either format to refer to a constant
print( $_CONSTANTS [ ‘FOO’ ]); //prints ‘bar’
print( FOO ); //prints ‘bar’
print( ” $_CONSTANTS [ ‘FOO’]” ); //prints ‘bar’
//prints ‘blah bar blah’
print blah < $_CONSTANTS [ 'FOO' ]>blah
EOF;

?>

Hope this helps some of you out there, I know being able to utilize my constants in HEREDOC helped me a ton!

*******



SOURCE: http://www.php.net/manual/en/function.define.php

Written by admin


%d bloggers like this: