What is Constants in PHP and it use?
Defining a Constant in PHP will help you if you are going to use a value through out your script. And as the name says CONSTANT means it’s a static value which cannot be changed.
To define a Constant in PHP all you have to do is use the default PHP function define()
Here is the example:
1 2 3 4 5 6 7 |
<?php define("WEBSITE", "tutorialsmade.com"); echo WEBSITE; ?> |
How this will be useful?
Lets take this example, you have a common PHP script and you are going to use it for several different domains:
1. exampleone.come
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php define('WEBSITE', 'http://exampleone.com'); ?> <html> <body> <img src="<?php echo WEBSITE; ?>/images/1.jpg" /> <a href="<?php echo WEBSITE; ?>/page/one.html" /> </body> <html> |
2. exampletwo.com
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php define('WEBSITE', 'http://exampletwo.com'); ?> <html> <body> <img src="<?php echo WEBSITE; ?>/images/1.jpg" /> <a href="<?php echo WEBSITE; ?>/page/one.html" /> </body> <html> |
So, the above two examples shows, the only value we have to change is the Constant ‘WEBSITE’, all the other places it will take the value automatically.