PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links 
search for in the  
previousVariables from outside PHPCostanti predefinitenext
Last updated: Tue, 03 Sep 2002
view the printer friendly version or the printer friendly version with notes or change language to English | Brazilian Portuguese | Chinese | Czech | Dutch | Finnish | French | German | Hungarian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Swedish | Turkish

Capitolo 9. Costanti

Una costante � un identificatore (nome) per un valore. Come si pu� intuire, tale valore non pu� cambiare durante l'esecuzione dello script (le costanti __FILE__ e __LINE__ sono l'unica eccezione). Una costante � "case-sensitive" per default. � convenzione comune che i nomi di costante siano sempre maiuscoli.

In PHP il nome di una costante segue le regole di qualsiasi "etichetta". Un nome di costante valido inizia con una lettera o underscore, seguita da un numero qualsiasi di caratteri alfanumerici o underscore. L'espressione regolare che esprime questa convenzione �: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Nota: In questo contesto una lettera � a-z, A-Z e i caratteri ASCII dal 127 al 255 (0x7f-0xff).

Una costante � sempre globale.

Sintassi

� possibile definire una variabile utilizzando la funzione define(). Una volta definita una variabile, non � possibile cambiarne il valore o eliminarla.

Le costanti possono contenere solo dati di tipo scalare (boolean, integer, double and string).

Per ottenere il valore di una costante � sufficiente specificarne il nome. A differenza delle variabili, non � necessario anteporre il simbolo $ al nome di una variabile. Si pu� anche utilizzare la funzione constant(), per leggere il valore di una costante, nel caso in cui se ne ottenga dinamicamente il nome. Si utilizzi get_defined_constants() per ottenere una lista delle variabili definite.

Nota: Costanti e variabili (globali) si trovano in un "namespace" differente. Questo implica che generalmente TRUE e $TRUE sono differenti.

Se si utilizza il nome di una costante che non � definita, PHP assume che detto valore sia il nome della costante stessa. Quando ci� accade PHP lo seganala il problema con con un notice. Per sapere se una costante � definita, si pu� utilizzare la funzione defined().

Di seguito sono riportate le principali differenze dalle variabili:

  • Le costanti non richiedono il simbolo di dollaro ($) anteposto al nome;

  • Le costanti si possono definire e utilizzare in qualsiasi contesto indipendentemente dalle regole dello spazio dei nomi;

  • Le costanti non si possono ridefinire o eliminare una volta che siano state definite; e

  • Le costanti possono contenere solo valori scalari.

Esempio 9-1. Definizione di costanti

<?php
define("COSTANTE", "Ciao mondo.");
echo COSTANTE; // stampa "Ciao mondo."
echo Costante; // stampa "Costante" e genera una notice.
?>

User Contributed Notes
Costanti
add a note about notes
[email protected]
29-Jan-2000 04:13

You can't define a constant that is another constant. In the same versions where define('FOO', TRUE) won't work, neither will define ('BAR', __LINE__). At least one of the DOS versions of php3 reliably demonstrates this behaviour. I'd call it a "no-no" to try and define a constant based on another constant.
[email protected]
05-Aug-2000 12:44

To get a full path (the equivalent of something like "__PATH__") use
dirname($SCRIPT_FILENAME)
to get the directory name of the called script and
dirname(__FILE__)
to get the directory name of the include file.

[email protected]
24-Jan-2001 12:54

It may be useful to note that, in php4 (what version this started I don't know, but it didn't do it before we upgraded to php4) __FILE__ will follow symlinks to the origional file.
[email protected]
09-Feb-2001 02:23

"SID" is defined also. It's the same as "session_name()=session_id()" and usufull for managing session using URL.
It's mentioned in Session reference, but I thought it would appropriate mention this section, too.

"NULL" is also defined and has null type. gettype(null) returns null and is_null($val) returns true for null - PHP4.0.4pl1 or later(?)

(I would like to know ALL constants defined by PHP in one place)

I also think that the class initilizer limitation intoruduced in PHP4 should be noted here.

PHP4 does not allow;

define ('C1',1);
define ('C2',2);
class foo {
var $val = C1 | C2;
}

Following code works.(PHP4.0.4pl1-linux)
define ('C1',1);
define ('C2',2);
class foo {
var $val = C1;
functin foo() {
$this->val = C1 | C2;
}
}

Details are explained

(thanks to hholzgra)

[email protected]
31-Mar-2001 05:38

If you use $PHP_SELF in forms or in places where a script has to reload itself, you will get the full path relative to the web root. This is very useful because it will always work, even if you move your script around on the server. You don't need to mess around with absolute or relative paths. An example would be:

<form method=POST action=$PHP_SELF?do_something> or
<a href=$PHP_SELF?do_something>Make script do something</a>

[email protected]
11-Jun-2001 05:42

The pre-defined constant '__FILE__' does not work in same way at every version of PHP.

Some version of PHP has the relative path, and some other has the absolute path on __FILE__ constant..

Please be carefull in use..

[PS]
I have not tested at all versions of PHP but the version of 4.04pl.. and 4.05 are certainly not working in same way.. If you want to see that bug(?), I can show you an example.

[email protected]
22-Jun-2001 06:52

Constants have the same naming rules as variables (though the docs don't actually say that). So you can't begin a constant name with a number.

if you name the
constant beginning with a numeral, such as:

define ("999CONSTANT", "some value");

whereas
define ("CONSTANT999", "some value");
works fine.

[email protected]
26-Aug-2001 12:10

Major difference between PHP3 and PHP4:
If you define a function that uses some constant C before you
define() C, C will be undefined in the function in PHP3 but not
in PHP4. Thus constants are more pre-processor-ish in PHP3,
but probably more useful in PHP4.

[email protected]
21-Feb-2002 06:28

Also predefined (in PHP 4.1.1 on linux) are a set of LOG_* constants such as LOG_DEBUG, LOG_ERR, LOG_WARNING, LOG_INFO, LOG_CRIT. I hit this when writing an external logging facility, and couldn't work out why some of my constants had the wrong values e.g.

<?php
define("LOG_DEBUG", 10);
print LOG_DEBUG;
?>

results in printing "7" rather than the "10" I had expected. This cost me about 15 minutes of grief. I would have expected some warning about trying to redefine a predefined constant.

[email protected]
25-Feb-2002 06:53

Warning, constants used within the heredoc syntax () 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.

[email protected]
23-Mar-2002 04:08

The __FILE__ constant in 4.2rc1 (CLI) will return the location of script specified to be run, rather than the absolute file.

eg. /usr/bin/phpmole (a softlink to /usr/lib/php/phpmole/phpmole.php)

started like this
bash#/usr/bin/phpmole

the line echo __FILE__ in phpmole.php will output /usr/bin/phpmole - in the CGI it would have returned /usr/lib/php/phpmole/phpmole.php

the workaround is to check for links!!
$f = __FILE__;
if (is_link($f)) $f = readlink($f);

[email protected]
18-Jul-2002 08:27

__FILE__ doesn't work with Zend Encoder 2.0.x (ZE does funky things with __FILE__).

This may be fixed in the future, but we don't know when. In the mean time, Zend has suggested we use the undocumented "zend_loader_current_file()", which seems to do the same thing as __FILE__ for me.

S

add a note about notes
previousVariables from outside PHPCostanti predefinitenext
Last updated: Tue, 03 Sep 2002
show source | credits | stats | mirror sites
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Thu Sep 5 20:07:53 2002 CEST