By 
PHP

PHP Made Easy for Beginners – Best Practices with Step by Step Checklist


Hi Guys, welcome again, hope everything is going great with your code :). Well this post is intended for the PHP programming beginners, if you an expert, sharing this post might help your followers who are beginners. So lets jump into the amazing stuff of PHP programming language.

What is Inside this Post:

·         Guide to PHP Tags

·         Best Practices for Coding

·         Using PHP Comments

·         Escaping from HTML

·         Multiline Syntax

·         PHP Constants with Best Practices

·         ECHO vs Print wih different variants

·         Types of variables and Scope

·         Easy Checklist of PHP Programming

Guide to PHP Tags

Your PHP parser will look for the following tags in your code file in order to determining a PHP code.

Anything within these tags will be considered as PHP code, and everything outside will be considered as HTML/text. Here is an example code;

Best Practices

·         You can use short tags for opening such as, ‘<? ‘, but this is highly discouraged. Never use this scheme

·         If your file is a pure PHP file, do not use PHP closing tag at the end of code file. This is to prevent unwanted whitespace and lines accidentally added at the end of the file after the closing PHP tag.

·         In PHP version 7, following ASP tags are not supported

          <%, %>, <%= , <script language=”php”>

·         In order to use PHP code in XML or XHTML, you need to use opening and closing PHP tags

PHP Comments

The most important part of a well organized code is to add proper comments. For each block of code, you should add comments describing what is happening. This is important so that your code can be understandable by other coder when needed.

·         PHP supports  C, C++, and Unix shell style comments e.g.

·         You can not comment PHP opening or closing tags such as //…?>

·         You can not nest /* and */ type of commenting

Escaping from HTML

You can use PHP and HTML together in a file because PHP ignores everything outside the opening and closing tags.  e.g.,

After the closing tag, PHP will start outputting any thing that comes into the way until it finds another PHP opening tag.

·         You can use escaping using PHP conditional statements like if, then, else

Example:

·         If you need to output a large block of text, it is preferred to drop out of PHP mode

·         There are five different types of PHP  opening and closing tags

Multiline Syntax

If you have too much to display, you can choose any of the following methods,

·         Assign value to a variable e.g. $var = “ add as much as you can “;

·         Use heredoc, its syntax is as follows,

This will output everything between _ABC tags.  You do not need to escape any special character when using heredoc method as it will display the text as it is.  You do not need to add ‘\n’ as well. Practical example is to use heredoc to display HTML, such as form.

You can assign the whole text within heredoc tags to a variable such as ;

Now you can use this variable any where. You can also use following operatore “.=” to append any string.  Make sure that semi colon is placed at the last tag. These tags can be any of your choice, and ABC is just for example purpose.

PHP Constants

Constants are the variables which hold fixed value, it means once you have defined the constant and assigned it a value, you can never change it lator. Here is how you define a constant in PHP,

To read the value of constant,

Interesting thing to note is that dollar sign is not used with the constant variable when reading.

Best Practices for PHP Constants

·         Constants should not be prefaced with dollar sign

·         Constants can only be declared with ‘define’ statement

·         A good practice is to use only uppercase letters for constants

There are some predefined  constants which you can also call PHP magic constants, which are below.

__LINE__
The current line number of a file.
__DIR__
This provides the directory of the file.
__FILE__
This provides the full path and filename.
__FUNCTION__
Returns the function name as it was declared.
__CLASS__
Returns the class name
__METHOD__
Returns the method name of a class as it was declared.
__NAMESPACE__
The name of current namespace

e.g. if you want to know the PHP file name and directory, use following,

PHP ECHO vs PRINT

Interesting thing to understand is the difference between echo and print PHP commands, both are used to output data such as,

both commands are correct so what is the difference?

First thing to note is that print can have a function like construct such as,

But it is not a function, this is the reason you can use it without brackets.

Printf

This is another variant of print command except that you can pass arguments in order to format the string such as,

The output will be 17 because we are requesting to print only decimal number. The format of command is as follows;

First parameter can be any of the following formats,

·         %% – Returns a percent sign

·         %b – Binary number

·         %c – The character according to the ASCII value

·         %d – Signed decimal number (negative, zero or positive)

·         %e – Scientific notation using a lowercase (e.g. 1.2e+2)

·         %E – Scientific notation using a uppercase (e.g. 1.2E+2)

·         %u – Unsigned decimal number (equal to or greather than zero)

·         %f – Floating-point number (local settings aware)

·         %F – Floating-point number (not local settings aware)

·         %g – shorter of %e and %f

·         %G – shorter of %E and %f

·         %o – Octal number

·         %s – String

·         %x – Hexadecimal number (lowercase letters)

·         %X – Hexadecimal number (uppercase letters)

You can insert additional format values between % sign and the number, which are;

·         + (Forces both + and – in front of numbers. By default, only negative numbers are marked)

·         ‘ (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %’x20s (this uses “x” as padding)

–          (Left-justifies the variable value)

·         [0-9] (Specifies the minimum width held of to the variable value)

·         .[0-9] (Specifies the number of decimal digits or maximum string length)

First argument is mandatory whereas other arguments are optional.

Example:

If you want to display floating number then,

Let us take another example,

Result: Pakistan was born in 1947, and its population is above 2 million

You can see in the above example that in place of first %d, 1947 is inserted and in place of second %d, second argument which is ‘2’ gets inserted. In this way, you can use following specifiers to format text.

Type Specifiers:

What if you want to display numbers with ‘+’ sign, because by default it will not. Use the following syntax,

Padding the output

Printf() also allows you to pad out resulting value to a fixed width.  Padding character can be any of your choice, furthermore;

·         If you do not use a padding character, then by default space is used.

·         If you want to use custom padding character, use single quotes

·         In order to specify padding width, a positive number will add padding to left whereas negative number will add padding to the right.

Examples

·         04 in above examples is the width of padding, means, a width of total 4 digits

·         Since 04 is positive number, therefore, two leading zeros will be added to the left of 99

·         In the above example, we have used a custom padding character which is ‘*’

·         Since the number 10 is negative, therefore, padding is added to the right of string ‘Hello’

·         10 is the total width of padding, means, a total of 10 digits

Number Precision

Printf() allows you to control the precision of number, e.g. by default if you use %f specifier then there will be 6 decimal places, if you want to lower the number of decimal places use below syntax,

Syntax: Use ‘.’ With precision number

Examples:

Assigning a result to a variable

If you want to save the output of print command in a variable, then use ‘sprintf()’ version just like below;

Types of Variables and Scope

Based on the scope of a variable, it can be classified into following;

·         Local variables

·         Global Variables

·         Static Variables

Local variables means you can not call them outside their container whether it be a function or a class. PHP parser will throw an error in case you try to access them outside a function/class in which they are specified.

Global variables are meant to be global, means you can use them any where within your namespace. In order to declare global variables, use following syntax,

global $counter;

You just have to place a keyword ‘global’ before a variable to make it global, now you can use it anywhere.

Best practices for Global Variables:

Try your best to avoid using global variables, and if so, try to minimize its usage.

In a large program, you can accidentally messup with values of global variables, making it hard to troubleshoot. Too many global variables means too many reasons for trouble.

Static Variables:

Static variables are local variables and they will keep the value till the program is running unlike normal variables.  The syntax is;

static $value = 100;

Memory location for the static variables remain same. A perfect example is to use them for counters.

Step by Step Checklist of PHP Syntax

·         Use semicolon at the end of each statement ‘;’

·         Use ‘$’ to declare a variable

·         PHP is loosely typed language, it means you do not have to declare the type of variable, if you save integer in a variable, then its type will be automatically integer e.g.

·         ‘Value’ is a literal whereas “Value” is a string. The difference is that  if you want to assign ‘as it is’ value to a variable then use string literal otherwise in PHP, you can use variables within string such as;

In the above example,  PHP will display the value of $variable. If you wanted to display it as it it, then use single quotes.

·         Variable names must start with a letter or underscore

·         Variable names can contain only characters a-z, A-Z, 0-9, and underscore

·         Variable names can not contain spaces

·         Variable names are case sensitive

Conclusion:

So guys, we have touched basics of PHP with best practices, tips from experts. In case you want to add something in this content, drop comments below. Thanks for taking out some time and reading my stuff.

Sohail ahmed
About me

Love to train and learn. SEO and development is my profession. 10+ years of IT training, practical experience in SEO. Creativity helps me strategize things well, especially when i code.

Leave a comment

Your email address will not be published. Required fields are marked *