OpenCart – PHP Basics Part 1 (Variables)

Opencart is an open source shopping cart application that is designed by means of MVC-L (Model-View-Control-Language). PHP is the server side scripting language that the entire cart is made up of. In this series we will discuss some PHP basics and how it relates to Opencart.

Variables

A variable can be looked at as a container for data. In every file, just about on every page of the Opencart you will see variables.

Basic bullet points about variables

A variable starts with the $ sign, followed by the name of the variable

A variable name must begin with a letter or the underscore character

A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

A variable name should not contain spaces

Variable names are case sensitive ($y and $Y are two different variables)

In short, without variables there would be no way of echoing all of the data from the database to the web page(s) that your customer will see. The control file will communicate with the template file at all times and the control tells the template file what to display by way of variables. To get a glimpse of this you need only open up any .tpl file in your folder but for this demo we instruct you to open catalog/view/theme/default/template/common/home.tpl

In this file at the very top you will see <?php echo $footer; ?>

The variable $footer displays the entire footer template and without it, would not appear. Notice the opening and closing php tags as well. These tags are necessary when using PHP. <?php ?>. You may ask yourself how can a variable so small hold such a large amount of data? Well, this is why variables are so important.

PHP Variable Scopes

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has four different variable scopes:

local

global

static

parameter

When you assign TEXT to a variable make sure to wrap it in quotations like this: $j = “Hello World”; If you want to declare an integer then just do $j = 5; conversely if you want a number string then $j = “5”; You can also give variables boolean values such as $j = true; or $j = false;