Opencart 2.0 – PHP Coding (Constants)

This article will explain the basics of what constants are and show you how to extend constants from the main configuration file in Opencart 2.0 as to be able to use them for extension development.

What are constants

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren’t actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]* (php documentation on constants)

In my description, a constant would be similar to a variable except that it is global across the entire script and cannot be changed of value. Constants can be used to store all types of things but mostly are used to store strings, and must always keep their case style unless set to not do so.

Here is an example of a constant:

In Opencart 2.0 open up config.php which is found in the root install location. You will see the following line of code:

define('HTTP_SERVER', '');

HTTP_SERVER can now be used anywhere the config.php file is called by simply doing the below procedure. This constant is called quite frequently and to find it you only have to run  a global search in your PHP IDE for HTTP_SERVER

<?php echo “My HTTP CONSTANT is called “.HTTP_SERVER ;?>

Now, to add a new constant to the existing config.php file simply copy and paste one of the existing, and change it to your liking. Like this:

define('ANIMAL_TYPE', 'zebra');

If you would like to see this constant show up in your opencart store you simply need to open any view file (.tpl) on the store front end and echo the constant like this:

<?php echo "My animal is: " . ANIMAL_TYPE;?>

Side notes

-Constants don’t always have to be called in a configuration file. In fact they can be defined just about anywhere. This is important to mention because the rule is that as long as it’s within the script. The script could start anywhere really.

-Here is an example of a constant that is NOT case sensitive:

define("GREETING", "Welcome to!", true);
echo greeting;

-Example of how they are indeed global

define("GREETING", "Welcome to!");

function myTest() {
    echo GREETING;

Looking for quality OpenCart Web Hosting? Look no further than Arvixe Web Hosting!

Tags: , , , | Posted under OpenCart | RSS 2.0

Author Spotlight

Joe Stenhouse

I am a web application developer that specializes in PHP, JAVASCRIPT, MYSQL, HTML, and CSS. We manifest exciting potentials within the world wide web through means of innovation.

Leave a Reply

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