Variables

   

You can also easily intertwine small segments of PHP into HTML, such as when printing out the value of a variable:

 <h1>Today's Date is <?= $date ?>.</h1>  

The "<?=" syntax in the php, when followed by a variable, is used as shorthand for the echo() function.

You can include comments in your PHP scripts. Comments are ignored by the Web server, and any comments contained within the PHP code are not sent to a browser. There are three forms of comments:

  • # Used just like it is used in PERL; comments out the remainder of the line after the # symbol.

  • // Used just like it is in JavaScript; comments out the remainder of the line after the // symbols.

  • /* and */ Comments out anything in between the two sets of symbols. This is the same syntax used in C to comment code.

Examples of comments in PHP code:

 <?  echo "Hello"; #prints out "Hello" echo "Hello"; //prints out "Hello" /* The following prints out "Hello" */ echo "Hello"; ?> 

You will most often see comments denoted using the // characters or the /* and */ characters. The # character is rarely seen, although it is still valid.

Variables in PHP are denoted by the "$". To assign the value "Hello World" to the variable $a, you simply call it in your code:

 $a = "Hello World";  

Strings must be enclosed by quotes, but they can contain variables themselves:

 $a = 4;  $string = "The value of a is $a"; // $string = "The Value of a is 4"; 

PHP variables do not have to be declared ahead of time, nor do they require a type definition. Note that you may get a warning about using undeclared variables if you try to use them before giving them a value (depending on how you set up error reporting in php.ini, see Chapter 8). For example:

 $a = 4;  $c = $a + $b; // $c = 4, but a warning appears "Warning: Undefined variable..". 

Warnings do not stop a script from continuing. If you forgot to add a semicolon at the end of one of the lines, then you would get a Parser error, which prohibits the script from running.

Since PHP variables are not typed, you don't have to worry about performing mathematical equations on the wrong type, as you might in C. For example:

 $a = 4;  $b = "5"; $c = $a + $b; // $c = 9; 

PHP also supports boolean variables, which can be assigned either a one or a zero, or the words true or false:

 $a = true;  $b = 1; //$a = $b $c = false; $d = 0; //$c = $d 

   
Top


Advanced PHP for Web Professionals
Advanced PHP for Web Professionals
ISBN: 0130085391
EAN: 2147483647
Year: 2005
Pages: 92

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