Chose Language:
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.

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

Constants are 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”

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. This constant is equivalent to dirname(__FILE__). The directory name does not have a trailing slash unless it is in the root directory.
__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. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__The name of the current trait. The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__The name of the current class method.
__NAMESPACE__The name of the current namespace.
ClassName::classThe fully qualified class name. See also ::class.

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