|
|
 |
define (PHP 3, PHP 4, PHP 5) define -- Define una constante por nombre Descripciónbool define ( string nombre, mixed valor [, bool insensible_mayusculas_minusculas] )
Define una constante por nombre. Vea la sección sobre
constantes para más detalles.
El nombre de la constante es dado por
nombre; el valor es dado por
valor.
El tercer parámetro, opcional,
insensible_mayusculas_minusculas
también está disponible. Si se entrega el valor
TRUE, entonces la constante será definida como
insensible a mayúsculas/minúsculas. El
comportamiento predeterminado es sensible a
mayúsculas/minúsculas; es decir, CONSTANTE y
Constante representan valores diferentes.
Ejemplo 1. Definición de Constantes |
<?php
define("CONSTANTE", "Hola mundo.");
echo CONSTANTE; echo Constante; define("SALUDO", "Hola tu.", true);
echo SALUDO; echo Saludo; ?>
|
|
Devuelve TRUE si todo se
llevó a cabo correctamente, FALSE en caso
de fallo.
Vea también defined(),
constant() y la sección sobre Constantes.
php at stock-conaulting dot com
16-Aug-2006 05:17
define() is a surpisingly expensive operation! If fast code execution is your primary concern, try to avoid define(). You may, for example, use a class with a number of const definitions instead; this will be significantly faster.
kramdar at gmail dot com
11-Aug-2006 05:41
I wrote this iffdefine function and I find that I use it all
over the place.
bool iffdefine ( string name, mixed value [, bool case_insensitive] )
It defines a constant if and only if (hense iffdefine) the
constant has not already been defined, otherwise do not
trigger an error or notice.
--kramdar
<?php
if ( !defined( 'iffdefine' ) )
{
function iffdefine( $name, $value, $case_insensitive = FALSE )
{
$nameMatch = '/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/';
$scalars = array( "boolean", "integer", "float", "string");
if ( !preg_match( $nameMatch, $name ) )
{
trigger_error(
"iffdefine: Invalid constant name: {$name}"
. "\nA valid constant name starts with a letter or"
. " underscore, followed by any number of letters,"
. " numbers, or underscores.",
E_USER_ERROR );
return FALSE;
}
else if ( !in_array( getType( $value ), $scalars ) )
{
trigger_error(
"iffdefine: Invalid value: "
. var_export( $value, true )
."\nThe value provided is not of scalar type: boolean,"
. " integer, float or string.",
E_USER_ERROR );
return FALSE;
}
else if( defined( $name ) )
{
return FALSE;
}
else if( !defined( $name ) )
{
return define( $name, $value, $case_insensitive );
}
}
}
?>
sean at syoft dot com
30-Jul-2006 11:21
I typically use
define('CONSTANT',serialize($value));
to store arrays in constants and then just unserialize as needed:
if(in_array('val',unserialize(CONSTANT))) {}
Didn't see this mentioned here previously.
m dot blanquett at gmx dot de
25-Jul-2006 07:35
If u have a bunch of definitions to handle, and want them to be really easy configureable, use this:
definitions.xml:
<definitions>
<definition>
<name>PROGRAM_NAME</name>
<value>Foo Bar</value>
</definition>
<definition>
<name>PROGRAM_VERSION</name>
<value>0.0.1</value>
</definition>
</definitions>
<?php
$defs = simplexml_load_file('definitions.xml');
foreach($defs->definition as $def) {
eval("define('{$def->name}', '{$def->value}');");
}
?>
Of course you can alter the xml format as you please, maybe like this (be aware, that you then need to change the php code to the new layout of the simple xml object.
<definitions>
<def name="PROGRAM_NAME" value="Foo Bar" />
<def name="PROGRAM_VERSION" value="0.0.1" />
</definitions>
xademax at gmail dot com
04-May-2006 05:46
<?php
class Define
{
var $Name;
var $Func;
function Define($Name, $Func)
{
$this->Name = $Name;
$this->Func = &$Func;
}
}
$DEFINES = array();
function set_define($Name, $Value, $Args)
{
global $DEFINES;
foreach($DEFINES as $DEFINE) if($DEFINE->Name == $Name) return false;
$DEFINES[] = new Define($Name, create_function($Args, 'return "' . $Value . '";'));
}
function get_define($Name, $Args = NULL)
{
global $DEFINES;
foreach($DEFINES as $DEFINE) if($DEFINE->Name == $Name)
{
$Func = $DEFINE->Func;
return eval('return $Func(' . implode(",", $Args) . ');');
}
return false;
}
?>
<?php
set_define("ERROR", 'There was an error : $error\n', '$error');
echo get_define("ERROR", array("pouet"));
?>
This Exemple will show :
There was an error : pouet
RQuadling at GMail dot com
08-Mar-2006 01:18
Yes. I did mistyped the base value.
And I only use the constants in their text form (the whole point of them really).
They are actually used in a XML structure as tags (now). Previously they where the keys in a massive multi-dimensional array.
If I added a new constant, nothing changed in terms of the data storage. If I removed one though, the data would not work and neither would the program using the data. Which is good news.
bobbykjack at yahoo dot co dot uk
18-Feb-2006 12:12
benjamin, I recognise your warning, but surely a key point of constants is that their values should NOT be referenced anywhere other than their definition.
richard, your solution could be made slightly safer with the use of a function for this process, e.g.
<?php
$iRuleVal = 0;
adefine ('RULE_CALLBACK_FORMAT');
adefine ('RULE_CHANGE_CALLBACK_ON_ERROR');
adefine ('RULE_CHANGE_COMPARE_DATE');
function adefine($constant_name)
{
global $iRuleVal;
if (defined($constant_name))
{
return;
}
define($constant_name, ++$iRuleVal);
}
?>
I think you also misnamed the original local variable - it should be $iRuleVal.
benjamin at metaconsult dot fr
07-Dec-2005 04:59
a warning for richard below (and who is reading the advice below).
When you remove constant in your pool, but already stored some of those values in a database or somewhere else as reference, you will surely mess up your application data !
So such an auto-definition for your constants is useful when you don't store those values anywhere else !
richard dot quadling at bandvulc dot co dot uk
01-Dec-2005 03:40
In trying to remove magic numbers from my code, I often use sets of defines. Some sets get quite big.
I sort my defines so that they are alphabetically arranged - for me this is easier.
The issue now comes as to what is the next available number or what happens to the number sequence if I remove a define.
My solution is to use the following mechanism.
<?php
$iRuleBase = 0;
define ('RULE_CALLBACK_FORMAT', ++$iRuleVal);
define ('RULE_CHANGE_CALLBACK_ON_ERROR', ++$iRuleVal);
define ('RULE_CHANGE_COMPARE_DATE', ++$iRuleVal);
define ('RULE_CHANGE_OLD_COLUMN', ++$iRuleVal);
define ('RULE_CHANGE_ON_DATE', ++$iRuleVal);
define ('RULE_DESC', ++$iRuleVal);
define ('RULE_EXPECTED_RESULT', ++$iRuleVal);
define ('RULE_LIMIT_TO_PERIOD', ++$iRuleVal);
define ('RULE_MATCH_ARRAY', ++$iRuleVal);
define ('RULE_MATCH_COLUMN', ++$iRuleVal);
define ('RULE_MESSAGE', ++$iRuleVal);
define ('RULE_REGEX', ++$iRuleVal);
?>
I no longer need to know ANY of the magic numbers. I can add and remove them at will and the code will show errors for the missing ones as the constant will be undefined. Much better than using the number and forgetting what entry 6 is.
You also have the value of $iRuleVal to indicate the next define if needed.
The defines then work like ...
<?php
$aGlobalValidationDefinitions = array(
'CH_SORT' => array
(
RULE_DESC => 'Contract on Cost Header / Project must match the Contract on the order.',
RULE_MATCH_COLUMN => 'POH_CONTRACT',
),
'CH_STATUS' => array
(
RULE_CHANGE_CALLBACK_ON_ERROR => 'dataentryValidateChanges',
RULE_CHANGE_COMPARE_DATE => 'POH_DATE_AUTH',
RULE_CHANGE_OLD_COLUMN => 'OLDSTATUS',
RULE_CHANGE_ON_DATE => 'VSC_DATECHANGED',
RULE_DESC => 'Vehicle Status must be A - Active or R - Reopened.',
RULE_LIMIT_TO_PERIOD => 'D',
RULE_REGEX => '^(?=[AR])(.)$',
),
'POD_COSTHEADER' => array
(
RULE_DESC => 'Must not start with "UNKNOWN".',
RULE_REGEX => '^(?!UNKNOWN)(.*)$',
),
);
?>
No magic numbers. You can add or remove defines without ever worrying about breaking the code and you never have 2 defines with the same value!
some at user dot com
30-Nov-2005 10:46
My hack at constant arrays :
function carray($const = null, $index = null)
{
static $carrays;
if ($const === null)
{
$i = count($carrays);
$carrays[$i] = $index;
return $i;
} else
{
return $index === null ? $carrays[$const] : $carrays[$const][$index];
}
}
function aconst()
{
$args = func_get_args();
if (count($args) == 1 && is_array($args[0]))
{
return carray(null, $args[0]);
} else
{
return carray(null, $args);
}
}
Use like this:
define('NRWORDS', aconst('zero', 'one', 'two', 'three'));
define('STUNT_DESC', aconst(array(
STUNT_TWOWHEELS => 'Two wheels',
STUNT_WHEELIE => 'Wheelie',
STUNT_STOPPIE => 'Stoppie'
)));
print(carray(NRWORDS, 2));
print(carray(STUNT_DESC, STUNT_WHEELIE));
$arr = carray(STUNT_DESC);
print_r($arr[STUNT_STOPPIE]);
bvr.
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'..
dsan at pml dot ac dot uk
08-Apr-2005 08:17
Just to clarify what 'david at nospam webgroup dot org' said:
${} is actually the syntax for 'variable variables'.
So in this specific case:
Starting with the line:
${MY_CONST} = serialize(array('foo' => 'bar'));
PHP will expand the constant and use it as the name of the variable:
$test = serialize(array('foo' => 'bar'));
So in fact there is no assignment to a constant (which would defy the definition of 'constant') but instead an assignment to a variable named by the _value_ of the constant.
david at nospam webgroup dot org
31-Mar-2005 03:14
To the comment posted by Raphael Crawford Marks:
You're actually manipulating the variable $test. The value of a constant obviously cannot be changed after it is set: hence the term constant. Try setting $test to something first, then running your code. It *WILL* be clobbered.
Raphael Crawford-Marks
10-Mar-2005 11:28
Notes on using serialize to store an array in a constant:
<?php
define('MYCONST','test'); ${MYCONST} = serialize(array("foo" => "bar")); echo "constant: ".${MYCONST};
echo "<br>";
$unserialized = unserialize(${MYCONST}); echo "unserialized: ".$unserialized['foo'];
?>
Note that you have to use ${} around the constant name for this to work.
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
tech at litigationdataservices dot com
25-Jan-2005 01:05
If your oft-used array is already defined, but the key value doesn't start at ['0'], --for example if you need an array of state names conforming to GIS codes, it's far easier to define the array in a low-level class and call it by
$classname->states[$STATEID];
than it is to try to define it as a constant or use an function to call it later from a free-standing array. It's also useful to do it this way when all you want to do is recall a fixed array value, but don't necessarily want to hit the database just to get it.
technopasta at yahoo dot com dot au
02-Jan-2005 05:55
You can't use arrays in constants, so I came up with this two line function to get around it.
<?php
function const_array($constant) {
$array = explode(",",$constant);
return $array;
};
?>
So now if you define a constant like
<? define('myconstant','item1,item2,item3') ?>
and then use my function
<? $myarray = const_array(myconstant); ?>
$myarray will now contain an array with
item1
item2
item3
Hope this is useful for someone...
konstantin #at schukraft #dot org
22-Sep-2003 03:13
Constants MUST evaluate to scalar values only.
You are encouraged to use serialize/unserlialize
to store/retrieve an array in a constant:
define('CONST',serialize(array('a','b','foo'=>'bar')));
var_dump(CONST);
var_dump(unserialize(CONST));
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");
${VAR_NAME} = "value";
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.
| |
| | Citas célebres | Los padres son las últimas personas del mundo que deberían tener hijos. Samuel Butler Compositor y novelista inglés (1835-1902) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Transportes | | La cremallera | En la parada del autobús, un nutrido grupo espera, en apretada fila, para subir al vehículo. Le llega el turno a una bella joven, quien viste altas botas y chaqueta a combinación con una estrecha minifalda de cuero.
La joven se percata de que el escalón de acceso al autobús es tan alto que la escueta faldita que porta le va a impedir subir. Sonrojada, se lleva las manos atrás, buscando la cremallera.
La localiza, la baja un poco y se dispone a subir.
Nada! Todavía la falda le impide levantar la pierna para alcanzar el escalón.
Mira avergonzada al chofer, sonríe tímidamente y, de nuevo, se lleva las manos atrás y baja un poco más la cremallera.
Pese a todo, aún la faldita le impide levantar la pierna para subir en este nuevo e inútil empeño.
La gente que espera en fila comienza a incomodarse y a protestar.
Un tipo grandote que esperaba su turno detrás de ella, toma a la muchacha, súbita y ágilmente, por la cintura, y la sube al autobús cual una pluma. La muchacha, furiosa, se vuelve al desconocido y le reclama:
- ¿Cómo se atreve a tocarme? ¡Descarado! Yo no sé quién es usted... !Fresco!
Y el hombretón, encogiéndose de hombros, le responde:
- Bueno, señorita, pensé que después de haber tratado de abrirme la bragueta dos veces seguidas... ya éramos amigos, ¿no? | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|