Cameron Garnett/Testpage7
Contents
Super Quick PHP Tutorial
Introduction | Basic Syntax | Sending Data to the Browser | Comments | Variables | Strings | Functions | Quotes | Debugging | Form
Learning ObjectivesBy the end of this page you will know how to declare variables using php code. |
VARIABLES
Variable's in PHP are very tricky because the are case-sensitive and must be named properly. There are certain rules that apply when you are naming your variables and they are as follows:
Rules for PHP variables
- A variable starts with the $ sign, followed by the name of the variable
- A variable name must start with a letter or the underscore character
- A variable name cannot start with a number
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive ($topic and $TOPIC are two different variables)
Output Variables
The PHP echo statement is often used to output data to the screen.
Example<?php |
When you assign a text value to a variable put quotes around the value. In the above example, once i execute the code the variable (fun) has a value of "Wikieducator" and the variable (pet) has a value of "dog".
In this next example i will show you how to add two variables together and then output the sum to the browser.
Example<?php echo $c + $a; |
the variable (c) has a value of 30 and the variable (b) has a value of 10. Because the value of these variables are numbers they do not need quotation marks.
ACTIVITYwrite the above block of code into notepad ++ and get yourself familiar with creating variables. |
Variable Scope
PHP variables have different scopes.
- Global
- Local
A variable that is created outside of a function() has a Global scope and can only be accessed outside of a function
A variable that is created Inside of a function() has a Local scope and can only be accessed inside of a function
ACTIVITYwrite the above block of code into notepad ++ and see how the variables work. |
Global Keyword
The Global Keyword is used to access a Global variable from within a function. This is done by writing the word Global before the variables inside your function.
Example<?php |
ACTIVITYwrite the above block of code into notepad ++ and see how the Global keyword is used to access the variables. |
Static Keyword
Most of the time when a function has been executed the variables are deleted and no longer exist. Sometimes we want the variables to remain so that we can use them again if we are using the same function.
This is done by writing the word static before you create the variable withing the function.
Example<?php |
ACTIVITYwrite the above block of code into notepad ++ and see how the staic keyword is used to reuse the variables. |