20 Nov 2012

Beginners Guide for PHP | Syntax and Variables




PHP is one of the most popular programming languages these days. For a website designer and developer it is recommended to learn this form basic to advance level.
In the series of our blogs of web development and design I will try my best to make you learn PHP in one of the easiest ways. Before you start you have to know some important starting points for PHP.
PHP is server side scripting. This is open source software and it is free to download and use.  If your server supports PHP then it is fine but if not you have to install it form some source.


Basic Syntax:
PHP starts always with <?php and end with ?>. PHP file contains .php extension. PHP contains some of the HTML Tags along with PHP scripting code.

Comments in PHP:
For the reuse purpose of PHP commenting is a good way. You should write Comments in front of every function. The commenting is written by adding /* in the beginning and */ at the end of your sentence.
Example: /* This is comment*/

Simple Program:
This is somehow similar to HTML syntax.
<html>
<body>

<?php
echo "Hello World";
?>

</body>
</html>

·         There are two basic statements echo and print.
·         Every code line ends with semicolon.

Variables:
Same like the algebraic variables we read in mathematics, php variables hold the values.
Like x=5, y=10 etc….and finally z= x+y.

Variable naming:
·         Starts with $ sign.
·         Name of the variable should start with underscore.
·         These can only be alpha numeric.
·         Can’t hold space in the naming.
·          Case sensitive.
·         Variable without any value is null variable.
·         Data type doesn’t need to define like we do in C or C++.

Example:
<?php
$txt="MyProgram!";
$x=16;
?>
There are four kinds of variable:
·         Local
·         Global
·         Static
·         Parameter

Local Scope:
<?php
$a = 5; // global scope

function myTest()
{
echo $a; // local scope
}

myTest();
?>

Global Scope:
<?php
$a = 5;
$b = 10;

function myTest()
{
global $a, $b;
$b = $a + $b;
}

myTest();
echo $b;
?>

Also it can be written as:

<?php
$a = 5;
$b = 10;

function myTest()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

myTest();
echo $b;
?>

Static Scope:
static $rememberMe;

Parameters: 

function myTest($para1,$para2,...)
{
// function code
}


So here were some basic practices for PHP. Remember! Only practice can make a person perfect in coding.

0 comments:

Post a Comment