Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

define

(PHP 3, PHP 4, PHP 5)

define -- Defines a named constant

Description

bool define ( string name, mixed value [, bool case_insensitive] )

Defines a named constant at runtime. See the section on constants for more details.

The name of the constant is given by name; the value is given by value.

The optional third parameter case_insensitive is also available. If the value TRUE is given, then the constant will be defined case-insensitive. The default behaviour is case-sensitive; i.e. CONSTANT and Constant represent different values.

Пример 1. Defining Constants

<?php
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."

?>

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

See also defined(), constant() and the section on Constants.



defined> <constant
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
define
Anonymous
15-Oct-2007 05:33
Note to the editor:

If it is so "obvious" that constants can't be redefined, then at least a warning should be issued if you try to redefine it.
john dot navratil at sbcglobal dot net
02-Oct-2007 07:38
Without really thinking, it is an easy assumption (especially for C coders) that defined constants are available after their lexical presence in a script.  It is, of course, temporally after the execution of the define statement.

All us knuckle-dragging C programmers may be tempted to write:

<?php
myEcho
("Hello, world");

define ("OUTPUT_FILE", "/tmp/asdf");
function
myEcho($msg) {
 
$f = fopen(OUTPUT_FILE, "a");
 
fwrite($f, $msg."\n");
 
fclose($f);
}
?>
and expect OUTPUT_FILE to be defined.  What you get is " Use of undefined constant OUTPUT_FILE - assumed 'OUTPUT_FILE' " because the 'define()' *FUNCTION* had not been called before its implicit use by myEcho().

Programming is always easier when one thinks, don't you think?
rayro at gmx dot de
15-Sep-2007 02:53
just a note to the previous post by e s lin d sey at g mail dot co m:

Well as u said, it is not the best workaround. To resolve this "Problem" without getting incredible loss of performance, you are able to make the use of "variable functions" like "variable variables":

<?php
$def
= 'constant';
$string = <<<END
    This is PHP running on<br />
   
{$def('PHP_OS')}
END;
var_dump($string);
?>

In this example we make use of the "constant" function which is builtin, and it will output:

string(37) " This is PHP running on
WINNT"

Tested on PHP 5...
Best regards
Joel
20-Aug-2007 05:36
If your constants don't show up in your included or required files, then you probably have php safe mode turned on!

I ran into this problem, I forgot to turn of safe mode when I was creating a new site.
e s lin d sey at g mail dot co m
13-Aug-2007 01:38
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:

<?php

//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:

<?php

//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:

<?php

//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 <<<EOF
  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!
smifffy at smith-net dot org dot uk
25-Jul-2007 04:23
a basic function to auto assign a numeric value that increase by itself each time - used in some permission style scripts

<?php
function define_bitwise($constant_name, $reset = False)
{
    static
$bitwise_next = 1;

    if (
$reset === True )
    {
       
$bitwise_next = 1;
    }

   
define($constant_name, $bitwise_next);
       
   
$bitwise_next += $bitwise_next;
}
?>

when reset it set to True, resets that value to 1 and starts afresh
creeves at dja dot com
19-Jul-2007 06:59
Intersting to note:

I found this in php5 on windows

If you try to unset a constant (which you cant but maybe you have a Jr. programmer or something).  The error message that is thrown is:

<?php
define
("SOME_CONSTANT", true);
unset (
SOME_CONSTANT);
?>

Parse error: parse error, unexpected ')', expecting T_PAAMAYIM_NEKUDOTAYIM
nl-x at bita dot nl
09-Jul-2007 10:34
Watch out. You can define a new constant with the name NULL with define("NULL","FOO");. But you must use the function constant("NULL"); to get it's value. NULL without the function call to the constant() function will still retrieve the special type NULL value.
Within a class there is no problem, as const NULL="Foo"; will be accessible as myClass::NULL.
dont care
03-Jun-2007 02:19
chris at frecod dot de, you might just use SQL for this:
NOT IN(var1,var2,var3,var4,var5,var6)
stangelanda at arrowquick dot com
31-Dec-2006 06:59
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:
<?php
function adefine($constant_name, $value=null) {
    static
$increment = 0; // 1 for bitmask

   
if (is_null($value)) {
       
define($constant_name, ++$increment); // $increment=$increment<<1 for bitmask
   
} 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.
<?php
adefine
('RULE_CALLBACK_FORMAT', 1); // 1
adefine ('RULE_CHANGE_CALLBACK_ON_ERROR'); // 2
adefine ('RULE_CHANGE_COMPARE_DATE'); // 3
adefine('KEYWORD', 'hodgepodge'); // hodgepodge <-- defined normally
adefine ('RULE_CHANGE_ON_DATE'); // 4

adefine ('ERROR_DESC', 1); // 1 <-- Counter reset
adefine ('ERROR_EXPECTED_RESULT'); // 2
?>
IK
15-Nov-2005 06:42
[Editor's Note: Obviously, constants cannot be redefined. That is the meaning of a constant.]

Just a quick note.. If a constant is once defined, any subsequent attempts to define it once again are ignored.

<?
define('WHAT_DID_YOU_EXPECT', 'First');
define('WHAT_DID_YOU_EXPECT', 'Second');
echo WHAT_DID_YOU_EXPECT
?>

Outputs 'First'.

I really thought I have gone mad when I saw just the last two lines of code (the first one was in another file) and it was echoing 'First'..
11-Feb-2005 08:45
Better pack with define() for all who really miss Java package management:

Use this "manifest.php" on very first script start or copy it to your config.somehow.php.

<?php
$__packages
= array(
   
"org.ilove.java.more",
   
"org.ilove.python.too",
   
"net.php.isok"
);

define("C_IS_WINDOWS", false);
define("C_DIR", (C_IS_WINDOWS ? "\\" : "/"));
define("C_PATH_ROOT", str_replace("/", C_DIR, $_SERVER["DOCUMENT_ROOT"]).C_DIR);
define("C_PATH_CORE", C_PATH_ROOT."core".C_DIR);
define("C_PATH_CLASS", C_PATH_CORE."classes".C_DIR);
define("C_APPLICATION_BASE", C_PATH_CORE.C_DIR."application".C_DIR);

$total_packages = 0;
$i = sizeof($__packages);
while(
$i-- > 0) {
   
$tokens = explode(".", $__packages[$i]);
   
$j = sizeof($tokens);
    while(
$j-- > 0) {
       
$token = strtolower(trim($tokens[$j]));
        if(
strlen($token) > 0 && !defined($token)) {
           
define($token, ($j == 0 ? C_PATH_CLASS : "").$tokens[$j].C_DIR);
           
$total_packages++;
        }
    }
}
define("C_PACKAGE_COUNT", $total_packages);
?>

With restrictions on non-package constants, you now can call your files like that:

<?php

require_once org.ilove.java.more."Than.php";

?>

Regards
Robi
phpnet at trenkner dot de
14-Mar-2003 03:59
---[Editor's Note]---
As of PHP 5.0.0 this is possible. You can define class-only constants, which can be called like Foo::Constant1 from the outside
---[End Note]---

Please keep in mind that

class AClass {
  define ("Const1", "Value1");
  ... }

didn't work. You have to make all your constant definitions before you open the class. So

define ("Const1", "Value1");
class AClass {
  ... }

would be correct.
radovan dot biciste at managestar dot com
06-Nov-2001 08:45
Wonder how to work with variable which name is stored in a constant?
Here it is:
<?php
define
("VAR_NAME","test");
// assigning value
${VAR_NAME} = "value";
// getting value back
echo ${VAR_NAME};
?>
ste at opk dot no
29-Aug-2001 10:41
To use a constant to show an element of an array inside a string:
define ('C', 0); print ("element 0: {$a[C]}");
The { & } around the variable signals that what's inside should be treated as a variable and not a string.
Note that 'print ("a constant:{C}");' wont work as ZERO is a constant.

defined> <constant
Last updated: Sat, 27 Jan 2007
 
 
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com
Z058440144362 Z348613067571