Variables, Operators, and Constants
Do you remember how your teachers introduced you to the concept of arithmetic in elementary class? If not, let me refresh your memory a little. Your teacher might have given you a simple example of a basket containing six tomatoes. She might have asked you to put a few more tomatoes in the basket.
آموزش طراحی سایت اختصاصی PHP – آموزش برنامه نویسی و طراحی اختصاصی سایت PHP
برای خرید بسته آموزشی طراحی سایت میتوانید به آدرس Webdesign.epaybank.ir مراجعه کنید تا با صنعت طراحی سایت و برنامه نویسی سایت آشنا و مسلط شوید.
Then you had to calculate the total number of tomatoes added to the basket, if the final number of tomatoes was eight. For our purposes, you might equate a variable with the basket and an operator with the process of calculating the total number of tomatoes kept in the basket.
In the previous chapters you learned the basics of PHP along with installation and configuration of PHP. In this chapter you will learn about variables, operators, and constants, which are the building blocks of any programming language. The first thing you’ll look at will be variables. Variables are an important part of writing any code, and you need to understand their use before you begin writing the code. Next you will learn about the different types of operators available in PHP and their use. Operators are used by variables or elements to perform calculations and to compare expressions. Finally, you will learn about constants and how you can use them effectively while writing your code.
Introduction to Variables
In the previous section I tried to explain the concept of variables by using an example of a vegetable basket. Let me generalize what variables actually are. Variables are entities that can hold different values over different periods of time.
Every programming language follows certain rules based on which variables are declared. These rules include the acceptable length of the variables, whether they can contain numeric or alphanumeric characters, whether the name of the variable can include special characters, and whether they can begin with a number. You will now look at the rules that should be followed while naming variables in PHP.
Rules for Naming Variables
In PHP, unlike some other programming languages, there is no restriction on the size of a variable name. In addition, you are free to use both numeric and alphanumeric characters in a variable name. However, there are certain rules that you need to follow. These include:
Variable names should begin with a dollar ($) symbol.
Variable names can begin with an underscore.
Variable names cannot begin with a numeric character.
Variable names must be relevant and self-explanatory.
Names like $a or $temporary might be understood and remembered while programming in the short run. However, it would be difficult to find out what they referred to later, when you or other developers look at the code after a long time.
Some examples and non-examples of variable names are:
Now that you have learned about the rules that need to be followed while naming variables, let me explain how to declare variables in PHP.
Declaring and Initializing Variables
Declaring variables implies specifying all the variables that you plan to use within the program. In programming languages like C and C++, these variables have to be declared explicitly along with their datatypes-for example:
However, in PHP you do not need to declare the datatype of the variable. You can declare a variable the first time you use it. This is because PHP does not force variables to belong to a specific datatype. The datatype of variables changes based on their content.
Initialization involves assigning values to variables. These values can belong to different datatypes. Datatypes in PHP can be divided into two types, scalar and compound. Scalar datatypes are simple datatypes that are found in most of the programming languages. These datatypes form the building blocks of a program written in any programming language. Scalar datatypes contain:
On the other hand, combining multiple simple datatypes together and storing them under one name creates complex datatypes. These datatypes are known as compound datatypes, and are used to store data belonging to different datatypes and to manipulate them. Compound datatypes can contain an:
Let me explain these datatypes individually.
Integer. An integer datatype can only contain whole numbers. These numbers can be either positive or negative. You use the ‘-’ symbol before the number to represent negative integers.
String. A string datatype is used to store a series of characters. A character is equal to a single byte of data. You can store 265 different types of characters in a string. However, in PHP there is no restriction on the size of a string.
Boolean. A boolean datatype can only contain either True or False. If you need to refer to the numeric value of a boolean value, True is represented by 1 and False by 0. This datatype is available only in PHP4.
Float. The float datatype is also used to store numbers. However, float values can also contain decimal numbers. You use the integer datatype to store non-decimal numbers.
Array. An array is used to store multiple values belonging to the same datatype. You can specify the length of an array while declaring it explicitly or at runtime. Each value stored in an array is called an element. You reference an element of an array and access its content by referring to its position within the array. You will learn in detail about arrays in Chapter 5, ‘Arrays.’
Objects. Objects are the integral part of any programming language. They contain not only data but also its functionality or what needs to be done with the data.
Following are some examples of assigning values to variables:
$Mystrval = “This is an example of a string value”;
$Myintval = 145665;
// An integer value
$Myboolval = True;
// A boolean value can either be True or False
$Myarrval = “My”;
//A array containing three elements
// A float value
$Myarrval = “First”;
//All three elements are referred to by the same
$Myarrval = “Array”;
// variable name.
In the above examples, you are directly assigning values to the variables. You can also assign values to variables by reference. Let me explain in detail about assigning values by reference.
Assigning Values to Variables by Reference
By default, each variable has its own unique value. This means that each variable has an area assigned to it in local memory that it uses to store its current value. Consider, for example, $empname=Timothy. Here the system assigns a memory location to the variable $empname, where the variable stores the value Timothy. If another variable needs to use this value, you need to assign the data explicitly. Therefore, the system needs to maintain multiple copies of the same data, which
leads to data redundancy. You can avoid this by assigning value by reference. In this case, the system maintains only a single copy of the data, which is referenced by all variables that require the value. Therefore, all the variables access the same area in the memory.
You can assign a value by reference by putting an ampersand (&) symbol in front of the variable name. This assigns the memory location of the data to the variable instead of creating another copy of the data.
Now that you know the rules that should be followed while specifying a variable name, consider the different scopes of variables. The scope of a variable in a program is the area where you can reference the variable directly.
Scope of Variables
The scope of a variable in a program determines whether other programs can access the variable from outside the parent program or whether parts of the same program can access the variable. The parent program is the program in which the variable is defined and initialized. The scope of a variable also determines when the system creates the variable in the memory and when it destroys it.
If you declare a variable inside a function or as an argument to a function, the scope of the variable is limited to local scope. This means that the variable can only be assigned a value or used inside the function in which it is declared. However, if you declare the variable outside the function, the scope of the variable is global. This means that you can use the variable or manipulate its value in any function.
Note You use a function to store a piece of code together and under one name. This provides easy reusability since you only need to specify the function name whenever you need to reuse code. Using functions also helps in debugging the code, as you only need to make a change in one place. Any change made to the code is cascaded across all references of the function. This makes the code easy to follow and understand. You will learn more about functions in Chapter 6, ‘Functions.’
In PHP, you can have either local or global variables. The scope of any variable declared within a function is by default limited to local. In PHP, a variable can be global by declaration, but it is still limited to local scope if you do not assign a value to it outside the function. In PHP, you need to declare variables as global and initialize them inside the function where they are used. This is unlike C, where a variable once defined as global is accessible within all functions. A function can contain an unlimited number of global variables. You will learn more about the variables in Chapter 6, in the section ‘Variable Functions and Variable Argument Functions.’
You might already know that most scripts or certain types of program codes execute on the client browser. However, certain types of scripts execute on a Web server; these scripts are known as server-side scripts. These server-side scripts use environment variables to pass information stored on a Web server to external programs requesting the information. These variables store information regarding the server, such as access and logon information. Although these variables are called environment variables, they are not related to the variables managed by the operating system. These variables manipulate information on the Web server. The only time these variables are used by the operating system is while passing information back to the program that had requested the information.
You can also set values for environment variables. Some of the common environment variables available in PHP and their functions are shown in Table 3-1.
Table 3-1: PHP Environment Variables and Their Functions Variable name
Contains all the arguments passed to a script from the command table text.
Contains a count of the number of arguments passed to a script from the command line.
Contains the name of the currently executing script. However, it is not available if PHP is run from the command line.
Contains an array of variables retrieved by using the HTTP GET method and is stored in the current script.
Contains an array of variables retrieved by using the HTTP POST method and is stored in the current script.
Contains an array of variables retrieved by using HTTP cookies and is stored in the current script.
Contains an array of variables stored in the current script by using the parent environment.
Contains an array of variables that have information regarding uploaded files. By using the HTTP POST method, you can upload these files.
Contains an array of variables passed to the current script by the HTTP server.
Now that you know about variables, let me tell you how you can further manipulate these variables. Manipulating variables involves performing mathematical, assignment, comparison, and concatenation operations on them. In order to manipulate variables, you need to use operators to perform these operations. PHP provides different types of operators to perform different tasks. The following section discusses these operators in detail.