Chose Language:
comments
Author: Admin/Publisher |finished | checked

PHP Constants

A constant is a value to which we assign a name, and this value will not change. For example, consider a value of a tax such as VAT.

We can see Constants, that are often used in WordPress configuration, as an example. Here’s how to define a constant.

By convention, the name of the constant is recommended to be in uppercase. A constant distinguishes between uppercase and lowercase letters.

The name of a constant must start with a letter or underscore. This one is defined using the define function

Ejemplos de constantes
<?php
//impuesto es distinto de impuesto escribir el nombre de una constante //en minusculas no es recomendado
define("IMPUESTO",2.5);
define("impuesto","hola");
?>

Well, we define a constant, but how do we use it?

<?php
   define("IMPUESTO",2.5);
   echo constant("IMPUESTO");
   echo IMPUESTO; //ambos impresiones darán lo mismo
?>

Constants can also be defined using the word “const” before the constant name. With “const”, you can define a constant inside or outside a class, but with “define” it can only be defined outside of classes in the global scope.

<?php
   const IMPUESTO = 22;
   echo IMPUESTO; //ambos impresiones darán lo mismo
?>

Predefined constants

PHP provides numerous predefined constants to any executing script. Many of these constants, however, are created by different extensions and will only be present if these extensions are available, either through dynamic loading or because they have been compiled. php.net

Predefined constant are also called “magic constants”

Magic Constants table

NameDescription
__LINE__ The current line number in the file.
__FILE__ The full path and filename of the file with symlinks resolved. If used inside an include, it will return the name of the included file.
__DIR__ The directory of the file. If used inside an include, it will return the directory of the included file.
__FUNCTION__ The name of the current function.
__CLASS__ The name of the current class. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4, __CLASS__ also works with traits
__TRAIT__ The name of the current trait. The trait name includes the namespace it was declared in
__METHOD__ The name of the current class method.
__NAMESPACE__ The name of the current namespace.
ClassName::class The fully qualified class name.

References: php.net

Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments