Php: Main - All your PHP needs!
In this tutorial, you will be learning how to create a constant, what a constant is, and how to use them.
-------------
What is a constant?
A constant is like a variable, except fore a few things, First, it is defined differently than a variable (you will learn how to define one later). Second, constants can not be changed or undefined. Third, constants can only hold string, integer/float (any number), and boolean values. And last, constants do not use the $ sign. Oh, and constants also don't follow variable scoping rules.
How do I create a constant?
To create a constant, you use the define() function. Example:
define(constant_name,constant_value);
Remember that constants follow variable rules when defining them. So, that means a constant name has to begin with a letter or underscore, not a number. Also, constants are cAsE-sEnSiTiVe so remember that ;). An example of defining a constant is below:
define("HELLO","world");
How do I output a constant's value?
To output a constant's value, you simply call its name. Say I have a constant HELLO with a value of world. If I wanted to output it, I would do:
echo HELLO;
//outputs world
If you tried something like this:
echo Hello;
It would output Hello, and you would get an error.
There is also another way to output a constant's value. This is done by the constant() function. Example:
echo constant(constant_name);
Example using the HELLO constant:
echo constant("HELLO");
//Outputs world
You are probably wondering why you would use constant() instead of just simply using the constant's name. This is because, for example, if you have the constant's name held somewhere dynamically in a variable. Look at this:
$constant="HELLO";
echo $constant;
//outputs HELLO
If you were doing something like this, you would probably want to output HELLO's value, not the exact word HELLO. So to do this, you would do:
$constant="HELLO";
echo constant($cons);
//outputs world
That is the best I can explain for using the constant() function.
Other functions to use with constants
There are a few other functions you can use with constants. I will list them and what they do below.
defined(constant_name);
The defined function is used to tell whether or not a constant exists. It will return true or false. Example:
define("WHAT","hi");
echo defined("RLY");
//outputs false because the constant RLY doesnt exist.
get_defined_constants()
This function returns an associative array or every defined constant. There is an optional parameter that can go in it, but I don't know anything about it, and don't feel like looking it up. Anyways, here is an example:
define("LOLWUT","dayum");
define("ORLY","yarly");
$constants=get_defined_constants();
echo $constants;
# theoretically, outputs:
dayum
yarly
but would really output Array #
-------------
That is the end of this tutorial! I hope you learned something new :)