In this PHP Tutorials – Variables And Constant, we are discussing that what are PHP variables and constants.PHP variables and constants both are used for holding value.But they have different characteristics as the purpose of usage. We know the variables are able to store anything inside it and constant are a fixed value which can not change.First, we look at PHP variables.
If you want to know what is PHP. You can also check our post Php Introduction.
What is PHP variables:
PHP variables are a blank space which filled by any value. Like a bucket which can be filled by water or either by salt. But First, we need to know that how we can define a variable in PHP.
How to create/declare variables in PHP:
In order to create/declare a variable in PHP. We need to write dollar sign ($) before a variable. Like this $variable.
Let see it in an example:
<!DOCTYPE html> <html> <body> <?php $x="this is a text"; // $x is a variable holding text (string) $y=10; // $y is a variable holding number (numberic) $z=0.10; // $z is a variable holding number (float) ?> </body> </html>
you can see that PHP variables can hold a string and numeric values and also float value too. So as we can see that it is very simple to create/declare PHP variable.In other languages first we need to declare their datatype then we declare variable but in PHP, as you write it become a variable.
What are PHP constants:
PHP constant value cannot change.So Php constant is such variables once their value is defined it become fix and cannot be changed. That’s why such variables are called PHP constant.
How to create/declare constants in PHP:
In order to create/declare a constant in PHP. we need a PHP function which is define() function. Like variables, constants are not simply declared. They need define() function.
There are two ways you can create a constant using define() function. First, we look at the syntax of define function.
Syntax : define(constant, constant value, constant variable case- sensitive/ insensitive).
There are 3 parameters are required to pass through a define() function for creating a PHP constant.
- A constant is a variable in which a value is holding.
- A constant value cannot change.
- A constant variable case-sensitivity is a boolean if it is true means constant is case-sensitive and if nothing means case insensitive.
Let’s take an example.
<!DOCTYPE html> <html> <body> <?php // Constant Type-1 define("HELLO", "This is value."); // case-sensitive constant echo HELLO; // Constant Type-2 define("HELLO", "This is value.", true); // case-insensitive constant echo hello; ?> </body> </html>
This is how we create variable and define constant in PHP.
Don’t forget to share this post on Facebook and other social sharing sites.