Constants And Variables

Constants and variable in PHP work much like they would in Java and many other languages. Variables are used to store values that can be used throughout the program. If you want to store a value but do not want it to be altered later, you can use a constant, which uses different syntax in PHP. Variables are set by using the $ tag in front of the variable name. The variable can then be set to any value. You do not need to declare a type like you would in other languages (int, string, double, etc.). Here is an example of code using variables and constants.

<?php
$value1 = 5;
$value2 = 7;
$value3 = 5+7;
$string = "Hello World";
define('FIRST_NAME', 'Tristan');  //a constant (nameOfVariable, setValue)
//constants
// define('greeting', 'hello world')
echo "$value1 $value2";
echo '<br />';
echo "$string";
echo '<br />';
echo FIRST_NAME;
echo '<br 0/>';
echo "$value1 + $value2"; //can't do math on variables in the echo comment
echo '<br />';
echo "$value3";
$value3 = $value1 * $value2;
echo '<br />';
echo "$value3";
 ?>

Like in HTML, the <br /> tag can be used to break to the next line. Notice there was no attempt to change the value of the constant throughout the program. Trying to do so would result in an error. The define() method creates a constant. The first value is the name of the variable, the second is the value it should be set to. 

To run this code you will need to run the MySQL database and the Apache server downloaded with XAMPP. 




Comments

Popular posts from this blog