Assigning Values to Variables

I l @ ve RuBoard

Assigning Values to Variables

I mentioned in the beginning of this chapter that you do not need to initialize or declare your variables. So how do you give them value in your scripts? You assign a value to a variable, regardless of the variable type by using the equal sign (=). Therefore, the equal sign is called an assignment operator, as it assigns the value on the right to the variable on the left. You will learn about the various types of operators throughout the next several chapters.

For example:

 $number = 1; $floating_number = 1.2; $string = "Hello, World!"; 

For better or worse , because variable types are not locked in (PHP is referred to as a " weakly typed" language, as is JavaScript), they can be changed on the fly:

 $variable = 1; $variable = "Greetings"; 

If you were to print the value of $variable now, it would print out "Greetings."

Tip

You'll learn about assigning values to arrays in Chapter 6, Using Arrays.


Tip

You can set the variable type by casting it upon first use (casting a variable is similar to declaring it, where you formally establish its type). The syntax for doing so is:

 $number = (integer) 5; $string = (string) "Hello, World!"; 

To be honest, there is little merit in doing this, but it is an option, if you would prefer to stay more consistent with other programming languages you use.


I l @ ve RuBoard


PHP for the World Wide Web (Visual QuickStart Guide)
PHP for the World Wide Web (Visual QuickStart Guide)
ISBN: 0201727870
EAN: 2147483647
Year: 2001
Pages: 116
Authors: Larry Ullman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net