Showing posts with label Syntax. Show all posts
Showing posts with label Syntax. Show all posts

Friday, February 8, 2008

Variables in PHP

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).

Note: $this is a special variable that can't be assigned.

<?php

$var = 'Bob';

$Var = 'Joe';

echo "$var, $Var"; // outputs "Bob, Joe"

$4site = 'not yet'; // invalid; starts with a number

$_4site = 'not yet'; // valid; starts with an underscore

$täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228.

?>

In PHP 3, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.

As of PHP 4, PHP offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:

<?php

$foo = 'Bob'; // Assign the value 'Bob' to $foo

$bar = &$foo; // Reference $foo via $bar.

$bar = "My name is $bar"; // Alter $bar...

echo $bar;

echo $foo; // $foo is altered too.

?>

One important thing to note is that only named variables may be assigned by reference.

<?php

$foo = 25;

$bar = &$foo; // This is a valid assignment.

$bar = &(24 * 7); // Invalid; references an unnamed expression.

function test()

{

return 25;

}

$bar = &test(); // Invalid.

?>

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type - FALSE, zero, empty string or an empty array.

Example: Default values of uninitialized variables

<?php

echo ($unset_bool ? "true" : "false"); // false

$unset_int += 25; // 0 + 25 => 25

echo $unset_string . "abc"; // "" . "abc" => "abc"

$unset_array[3] = "def"; // array() + array(3 => "def") => array(3 => "def")

?>

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

Tuesday, February 5, 2008

Comments in PHP

PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments. For example:

<?php

echo 'This is a test'; // This is a one-line c++ style comment

/* This is a multi line comment

yet another line of comment */

echo 'This is yet another test';

echo 'One Final Test'; # This is a one-line shell-style comment

?>

The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?> or # ... ?> WILL be printed: ?> breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that. If the asp_tags configuration directive is enabled, it behaves the same with // %> and # %>. However, the </script> tag doesn't break out of PHP mode in a one-line comment.

<h1>This is an <?php # echo 'simple';?> example.</h1>

<p>The header above will say 'This is an example'.</p>

'C' style comments end at the first */ encountered. Make sure you don't nest 'C' style comments. It is easy to make this mistake if you are trying to comment out a large block of code.

<?php  

/*

echo 'This is a test'; /* This comment will cause a problem */

*/

?>

Instruction separation in PHP

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present.

   

<?php

echo 'This is a test';

?>

<?php echo 'This is a test' ?>

<?php echo 'We omitted the last closing tag';

Note: The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include() or require(), so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.

Tuesday, January 29, 2008

PHP Basic syntax

Escaping from HTML

When PHP parses a file, it looks for opening and closing tags, which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows php to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. Most of the time you will see php embedded in HTML documents, as in this example.

<p>This is going to be ignored.</p>

<?php echo 'While this is going to be parsed.'; ?>

<p>This will also be ignored.</p>

You can also use more advanced structures:

Example#1 Advanced escaping

 

<?php

if ($expression) {

?>

<strong>This is true.</strong>

<?php

} else {

?>

<strong>This is false.</strong>

<?php

}

?>

This works as expected, because when PHP hits the ?> closing tags, it simply starts outputting whatever it finds (except for an immediately following newline - see instruction separation ) until it hits another opening tag. The example given here is contrived, of course, but for outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo() or print().

There are four different pairs of opening and closing tags which can be used in php. Two of those, <?php ?> and <script language="php"> </script>, are always available. The other two are short tags and ASP style tags, and can be turned on and off from the php.ini configuration file. As such, while some people find short tags and ASP style tags convenient, they are less portable, and generally not recommended.

Note: Also note that if you are embedding PHP within XML or XHTML you will need to use the <?php ?> tags to remain compliant with standards.

Example#2 PHP Opening and Closing Tags

 

1. <?php echo 'if you want to serve XHTML or XML documents, do like this'; ?>

2. <script language="php">

echo 'some editors (like FrontPage) don\'t

like processing instructions';

</script>

3. <? echo 'this is the simplest, an SGML processing instruction'; ?>

<?= expression ?> This is a shortcut for "<? echo expression ?>"

4. <% echo 'You may optionally use ASP-style tags'; %>

<%= $variable; # This is a shortcut for "<% echo . . ." %>

While the tags seen in examples one and two are both always available, example one is the most commonly used, and recommended, of the two.

Short tags (example three) are only available when they are enabled via the short_open_tag php.ini configuration file directive, or if php was configured with the --enable-short-tags option.

Note: If you are using PHP 3 you may also enable short tags via the short_tags() function. This is only available in PHP 3!

ASP style tags (example four) are only available when they are enabled via the asp_tags php.ini configuration file directive.

Note: Support for ASP tags was added in 3.0.4.

Note: Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server. For portable, redistributable code, be sure not to use short tags.