How to define constants in PHP and what is the use?

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:

<?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

<?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

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

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top