ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

A Server Side Web Tutorial Series # 2 - PHP Initialization, Comments, Error Reporting, Variable Type & Scope

Updated on April 7, 2014

Recap of The Last Tutorial

In our last tutorial,A Server Side Web Tutorial Series # 1 - An Introduction to PHP, An Open Source Server-side Scripting Language the first one in this series we discussed the features an advantages of using PHP as a server-side scripting language. We also noted that although one can simply download and install PHP singly, there are advantages in install the XAMPP package (or its variant for UNIX. LINUX, or Mac OS X) for a developer who is not merely interested in PHP as a general purpose programming language but as one piece in the puzzle of creating robust web pages and web sites.

We concluded the tutorial by giving a simple example of echoing some text to the screen and looked at the built-in phpinfo() function output and mentioned that an often used method of doing MySQL administration is by the use of phpMyAdmin.


The Focus of This Tutorial is to Cover Preliminaries

Comments and indenting code help to document your code and make it more readable. Indentation can can reflect things about nesting and structure of a program. We will point this out from time to time.

Comments are a way of documenting the code. A good preamble telling the “where. when, how, and why” is a great way of telling more about your code than even a well chosen file name can.

There are two types of comments supported in PHP. A single line comment preceded by two forward slashes and a block comment enclosed within a beginning /* and an ending */. The following snapshot illustrates the use of both.


Illustration of Block and Single Line Comments

In this snapshot we see a block comment, as a preamble to the program and change log. Block comments are encapsulated by /* and */. Single line comments denoted with // can appear on a line by themselves or at the end of a line.
In this snapshot we see a block comment, as a preamble to the program and change log. Block comments are encapsulated by /* and */. Single line comments denoted with // can appear on a line by themselves or at the end of a line.

The PHP Configuration File, php.ini

The php.ini file (contained in the php subdirectory of the xampp installation directory) contains the configuration details for PHP. When you run phpinfo() from the XAMPP display you will see some of these values in the output, but to get to the heart of the configurable parameter you should work with the php.ini file directly.

The point ofl looking at this file at this early stage in out PHP tutorials is this: there is one parameter you absolutely may need to change right now. The parameter name is error_reporting which may be set to 0, in which case no errors would be reported to the web page being displayed. The following snapshot illustrates the situation. In this case, error_reporting is set to E_ALL and the parse error is reported. The initial setteing had been error_reporting=0, in which case absolutely nothing was written to the screen. In this case even trying to do an “inspect element” by clicking on the browser window did not show any helpful information.

Why would the php.ini have error_reporting turned off?

It really is a matter of security. If error_reporting was turned on your implementation is visible to whoever might want to “make mischief”. For development is a good thing to see all errors, for production purposes you would probably want it turned off.

Note also, just changing the value in the php.ini file does not correct the problem. “php.ini” is read only at startup. To fix the problem, the Apache service must be restarted.

There Is No Error Reporting IF It Is Turned Off

This error message appears in the browser window if error_reporting is set properly. In our case in development we have the value set to E_ALL
This error message appears in the browser window if error_reporting is set properly. In our case in development we have the value set to E_ALL
Look at how PHP handles an error with respect tot he source code. For this I right-clicked and selected "inspect element'".
Look at how PHP handles an error with respect tot he source code. For this I right-clicked and selected "inspect element'".

Variables in PHP

First of all, PHP has no explicit way to declare a variable. A variable is declared when a value is assigned to it. Thus, PHP is defined as a loosely typed language (as opposed to strongly typed languages where variable assignment is allowed based on the variable's defined type). PHP does have very explicit rules for the naming of variable, however. A variable to be legal in PHP must follow these rules:

  • All variable names must start with the $ sign, followed by valid characters

  • A variable name to be must valid must follow the $ sign with a letter or the underscore character

  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

  • A variable name cannot contain spaces

  • Variable names are case sensitive

The snapshot which follows indicates the types of values which can be represented in PHP: integers, decimal values, exponential values, strings. Numeric values can be both positive or negative. In a variable assigned a exponential value the “e” is not case sensitive (i.e. 8e5 evaluates the same as 8E5).

Illustration of Variable Types

Some very simple assignments and echoing of the variables: integer, negative, decimal, exponential, string. Note the concatenation of a sting and a numeric value.
Some very simple assignments and echoing of the variables: integer, negative, decimal, exponential, string. Note the concatenation of a sting and a numeric value.

Variable Scope in PHP

Besides variable type which was mentioned above, variables have scope. That is how and where variables are “known”, where a variable can be referenced.

PHP exhibits four different variable scopes;

  • local

  • global

  • static

  • parameter

A local variable can only be used in the function in which it is defined.

A global variable is a variable which is defined outside of any function. It can be used in a script anywhere except within a function. To reference a global variable within a function it MUST be in a statement within the function and preceded by the keyword global or it can also be described with as element in a special array, $GLOBALS, which is an associative array, whose index is the variable's name. For example if one wanted to use the variable x, a global variable within a function we could either write the statement “global x;” or “ $GLOBALS['x']” where it is referenced.

When a function completes, all of its local variables by default are destroyed. If for some reason, you which for the value of a variable to remain “alive” after a function exits, you would use the keyword static with the variable.

Parameter variables are local variables which are passed as arguments to a function. Essentially, the variable name is a convenience. If for example a function caller had some reason to send the value 5 to a function. They could pass the value 5 to the receiving function in an argument list. It would not matter what the name was in the argument list, provided that that name was also used for the intended purpose in the body of the function. The name used in the argument list is a placeholder.

The subject of variable scope will be addressed further when program and function structure are discussed.

String Variables

String variables are distinguished from their numeric counterparts in that strings are enclosed within quotes, either double or single quotes as long as they are balance around their enclosed value. Thus,

$x = 5 assign the number 5 to the variable $x. $x can now be used in calculations.

$x = “5”; or $x ='5'; indicates a string.

We conclude this tutorial with a brief discussion of using string variables with the PHP concatenation operator and some built-in functions.

The concatenation operator, designated by the (.) period symbol is a way of joining two or more strings together. The period is placed between the strings being joined. When an assignment is made the assigned variable is the aggregate of the two strings.

Some useful string functions are:

strlen() - returns the value of the number of characters included in the string.

strpos() - returns the value of either a character or string of characters in the string passed to it.

strrev() - returns a string in reverse order.

rtrim(), ltrim(), trim() - removes leading blanks from the right end of the string, the left end of the string, or both ends of a string.

The snapshot which follows demonstrates the use of these functions.

Using Several PHP functions

We assigned a value to a string and then used strlen() to obtain the lenght of the string. This often comes in hand. We also used strpos() to locate the beginning of the word "string" in the string.
We assigned a value to a string and then used strlen() to obtain the lenght of the string. This often comes in hand. We also used strpos() to locate the beginning of the word "string" in the string.

Wrap Up and What's Next

We looked at indentation and comment help to make a program more readable. Preamble comments should indicate the purpose of a program and document the changes and by whom they were performed.

We looked at the php.ini file and noted that error_reporting can be turned off by default> We looked at variable of various types and most importantly the naming conventions which must be followed to create valid variables. The types of variable scope was discussed. Improperly scoped variable often lead to subtle and hard to find errors.

We wrapped up with several of the many built-in functions.

In the next tutorial we will cover all of the types of operators in PHP.


Please Rate This Tutorial Based on Clarity & Compleness

Cast your vote for Did this tutorial meet your expectations?
working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)