Advanced Web Development-Lecture 2
Advanced Web Development-Lecture 2
•Variables
•String functions
PHP Comments
Comments in PHP
A comment in PHP code is a line that is not executed as a part of the
program. Its only purpose is to be read by someone who is looking at
the code.
Comments can be used to:
• Let others understand your code
• Remind yourself of what you did - Most programmers have
experienced coming back to their own work a year or two later and
having to re-figure out what they did. Comments can remind you of
what you were thinking when you wrote the code
PHP supports several ways of commenting:
Single-line example
Syntax for single-line comments:
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
</body>
</html>
Multiple-Line example
Syntax for multiple-line comments:
<!DOCTYPE html>
<html>
<body>
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
</body>
</html>
Using comments to leave out parts of the code:
<!DOCTYPE html>
<html>
<body>
<?php
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
PHP Variables
Variables are "containers" for storing information.
Creating (Declaring) PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the
variable:
<?php
?>
After execution of the statements above, the
variable $txt will hold the value Hello
world! , the variable $x will hold the value 5,
and the variable $y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around
the value.
$txt = "W3Schools.com"; $x = 5;
echo "I love $txt!"; $y = 4;
echo $x + $y;
?>
?>
PHP is a Loosely Typed Language
In the example above, notice that we did not have
to tell PHP which data type the variable is.
function myTest() {
// using x inside this function will generate an
error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
PHP The static Keyword
Normally, when a function is completed/executed, all of its variables are deleted.
However, sometimes we want a local variable NOT to be deleted. We need it for a
further job.
To do this, use the static keyword when you first declare the
variable:
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
PHP String Functions
A string is a sequence of characters, like "Hello world!".