Like any programming language, PHP supports the use of variables to store data. However, there are several unique characteristics of PHP that should be remembered when working with them.
The syntax for creating variables in PHP:
- $X=5;
1. All PHP variables must start with the '$' character.
I agree that it's kind of strange, but once I could see where a universal starting character would be helpful in easily identifying all variables in a program.
Examples
- If you wanted a variable called X, you would have to create it as $X
- If you wanted a variable called 'textstring' you would have to create it as $textstring
2. PHP is a loose language.
So you probably know that it many other programming languages declaring the type of information that a variable will hold is important. Not in PHP. PHP automatically determines a variable's type based on the value that is first assigned.
Examples:
- If you set your variable '$X' to equal 5, PHP will automatically store its data type as an integer.
- If you set your variable '$textstring' to equal "Hello World", PHP will automatically store its data type as a string.
3. In PHP, declaring and assigning a value to a variable must happen in the same step.
In many other programming languages it is possible to declare a variable on one line, and then assign it its first value at another point in the program. Because PHP determines the variable type based off of the value given to it (see point 2), it is necessary that you give each variable a value during the declaration stage.
Example:
- Allowed: $X=5;
- Not Allowed: $X;
No comments:
Post a Comment