PHPs two data types resource and NULL are classified as special types. An object of resource type refers to external resources like database connection, file streams etc. On the other hand, a NULL data type is a variable without any data assigned to it. In this chapter, we shall learn more about these types.
Resource Type
A PHP program often needs to interact with an external environment such as a database, or a disk file etc. These are treated as resources in PHP. Resource is a special data type that refers to any such external resource. PHP uses relevant functions to create these resources. For example, fopen() function opens a disk file and its reference is stored in a resource variable.
PHP’s Zend engine uses reference counting system. Hence, a resource with zero reference count is destroyed automatically by garbage collector and the memory used by resource data type need not be freed manually.
Different built-in PHP functions return respective resource variables. Subsequently, PHP uses them for interacting with the corresponding external environment. For example, the fopen() function returns a file resource, which acts as a file handle and the read/write operations on the file are facilitated by this resource variable.
The following table summarizes different functions that return resource variables −
Resource Type
Built-in functions
Definition
Produced
Sold
bzip2
bzopen()
bzclose()
Bzip2 file
curl
curl_init()
curl_close()
Curl session
ftp
ftp_connect(),
ftp_close()
FTP stream
mssql link
mssql_connect()
mssql_close()
Link to Microsoft SQL Server database
mysql link
mysql_connect()
mysql_close()
Link to MySQL database
mysql result
mysql_db_query(),
mysql_free_result()
MySQL result
oci8 connection
oci_connect()
oci_close()
Connection to Oracle Database
ODBC link
odbc_connect()
odbc_close()
Link to ODBC database
pdf document
pdf_new()
pdf_close()
PDF document
stream
opendir()
closedir()
Dir handle
stream
fopen(), tmpfile()
fclose()
File handle
socket
socket_create()
Socket_close()
Socket handle
xml
xml_parser_create()
xml_parser_free()
XML parser
zlib
gzopen()
gzclose()
gz-compressed file
zlib.deflate
deflate_init()
None()
incremental deflate context
zlib.inflate
inflate_init()
None()
incremental inflate context
PHP has get_resource_type() function that returns resource type of a variable.
get_resource_type(resource$handle):string
where $handle is the resource variable whose type is to be obtained. This function returns a string corresponding to resource type.
There is also get_resource_id() function an integer identifier for the given resource.
get_resource_id(resource$resource):int
Example
This function provides a type-safe way for generating the integer identifier for a given resource.
<?php
$fp = fopen("hello.php", "r");
$resource = get_resource_type($fp);
$id = get_resource_id($fp);
echo "The resource type is : $resource The resource ID is : $id";
?>
It will produce the following output −
The resource type is : stream The resource ID is : 5
NULL type
In PHP, a variable with no value is said to be of null data type. Such a variable has a value defined as NULL. A variable can be explicitly assigned NULL or its value been set to null by using unset() function.
$var=NULL;
It is possible to cast variable of other type to null, although casting null to other type has been deprecated from PHP 7.2. In earlier versions, casting was done using (unset)$var syntax
Example
The following example shows how to assign NULL to a variable
<?php
$var=NULL;
var_dump($var);
?>
It will produce the following output −
NULL
Example
The following example performs null variable to other primary variables −
Prior to version 7, PHP parser used to report errors in response to various conditions. Each error used to be of a certain predefined type. PHP7 has changed the mechanism of error reporting. Instead of traditional error reporting, most errors are now reported by throwing error exceptions.
The exception handling mechanism in PHP is similar to many other languages, and is implemented with the try, catch, throw and finally keywords.
The Throwable Interface
Exceptions in PHP implements the Throwable interface. The Throwable interface acts as the base for any object that can be thrown via throw statement, including Error and Exception objects.
A user defined class cannot implement Throwable interface directly. Instead, to declare a user defined exception class, it must extend the Exception class.
PHP code with potential exceptions is surrounded in a try block. An exception object is thrown if it is found, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch or finally block. Moreover, there may be more than one catch/finally blocks corresponding to a try block.
try{// throw errors in the try-block // if an error occurs we can throw an exceptionthrownewException('this is an error.');}catch(Exception$e){// catch the throws in the catch-block // do something with the exception object, eg. // display its messageecho'Error message: '.$e->getMessage();}
If an exception is thrown and there is no catch block, the exception will “bubble up” until it finds a matching catch block. If the call stack is unwound all the way to the global scope without encountering a matching catch block, a global exception handler will be called (if it is set) otherwise the program will terminate with a fatal error.
set_exception_handler
This function sets the default exception handler if an exception is not caught within a try/catch block. After the callback is executed, the program execution will stop.
The $callback parameter is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown.
The function returns the name of the previously defined exception handler, or NULL on error. If no previous handler was defined, NULL is also returned.
Example
Take a look at the following example −
<?php
function handler($ex) {
echo "Uncaught exception is : " , $ex->getMessage(), "\n";
}
set_exception_handler('handler');
throw new Exception('Not Found Exception');
echo "not included Executed\n";
?>
It will produce the following output −
Uncaught exception is : Not Found Exception
SPL Exceptions
Standard PHP library contains predefined exceptions −
Sr.No
Predefined Exceptions
1
LogicExceptionException that represents error in the program logic.
2
BadFunctionCallExceptionException thrown if a callback refers to an undefined function or if some arguments are missing.
3
BadMethodCallExceptionException thrown if a callback refers to an undefined method or if some arguments are missing.
4
DomainExceptionException thrown if a value does not adhere to a defined valid data domain.
5
InvalidArgumentExceptionException thrown if an argument is not of the expected type.
6
LengthExceptionException thrown if a length is invalid.
7
OutOfRangeExceptionException thrown when an illegal index was requested.
8
RuntimeExceptionException thrown if an error which can only be found on runtime occurs.
9
OutOfBoundsExceptionException thrown if a value is not a valid key.
10
OverflowExceptionException thrown when adding an element to a full container.
11
RangeExceptionException thrown to indicate range errors during program execution. An arithmetic error other than under/overflow.
12
UnderflowExceptionException thrown when performing an invalid operation on an empty container, such as removing an element.
13
UnexpectedValueExceptionException thrown if a value does not match with a set of values.
User-defined Exception
You can define a custom exception class that extends the base Exception class. Following script defines a custom exception class called myException. This type of exception is thrown if value of $num is less than 0 or greater than 100.
Example
The getMessage() method of Exception class returns the error message and getLine() method returns line of code in which exception appears.
<?php
class myException extends Exception {
function message() {
return "error : ". $this->getMessage(). "in line no". $this->getLine();
}
}
$num=125;
try {
if ($num>100 || $num<0)
throw new myException("$num is invalid number");
else
echo "$num is a valid number";
}
catch (myException $m) {
echo $m->message();
}
?>
Run the above code with $num=125 and $num=90 to get an error message and a message of valid number −
Standard distributions of PHP have the JSON support enabled by default. The PHP extension implements the JavaScript Object Notation (JSON) data interchange format. The JSON extension in PHP parser handles the JSON data.
JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data interchange format. JSON defines a small set of formatting rules for the portable representation of structured data. It is a text based data format that is easy for the humans as well as machines to read.
The JSON extension in PHP version 5.2 onwards provides a number of predefined constants, JSON related functions, and also a JsonException class.
PHP JSON Functions
PHP has the following JSON functions −
json_encode()
This function returns a string containing the JSON representation of the supplied value. If the parameter is an array or object, it will be serialized recursively.
When the associative parameter of this function is true, JSON objects will be returned as associative arrays; when false, JSON objects will be returned as objects.
The encode/decode operations are affected by the supplied flags. The predefined constants and their integer values are as below −
Predefined Constant
Values
JSON_HEX_TAG
1
JSON_HEX_AMP
2
JSON_HEX_APOS
4
JSON_HEX_QUOT
8
JSON_FORCE_OBJECT
16
JSON_NUMERIC_CHECK
32
JSON_UNESCAPED_SLASHES
64
JSON_PRETTY_PRINT
128
JSON_UNESCAPED_UNICODE
256
json_last_error_msg()
This function returns the error string of the last json_encode() or json_decode() call.
json_last_error_msg():string
“No error” message is returned if no error has occurred.
json_last_error()
This function returns an integer.
json_last_error():int
The function returns an integer corresponding to one of the following constants −
Sr.No
Constant & Meaning
1
JSON_ERROR_NONENo error has occurred
2
JSON_ERROR_DEPTHThe maximum stack depth has been exceeded
3
JSON_ERROR_STATE_MISMATCHInvalid or malformed JSON
4
JSON_ERROR_CTRL_CHARControl character error, possibly incorrectly encoded
It is important that the input data received in the form of client request is validated before processing in a PHP application. To perform input validation, the filter extension in PHP provides a number of filter functions, backed up by predefined filter constants and flags. The filter extension of PHP library also helps in sanitizing the input received by either GET or POST methods.
The filter extension is a powerful feature that helps prevention of security vulnerabilities, such as SQL injection and cross-site scripting. The extension has two types of filters −
Validation Filters
Validation filters check if the data meets certain criteria. For example, you want to ensure that the user has correctly input an email field in the HTML form. The FILTER_VALIDATE_EMAIL will determine if the data is a valid email address. The validation filters, however, will not change the data itself.
Sanitization Filters
Sanitization refers to the process of removing undesired characters from the input. Hence, it may alter the data by removing undesired characters. For example, passing in FILTER_SANITIZE_EMAIL will remove characters that are inappropriate for an email address to contain, without performing validation.
Filter Flags
The filter extension in PHP defines a number of filter flags as follows −
Sr.No
ID & Description
1
FILTER_FLAG_STRIP_LOWStrips characters that have a numerical value <32.
2
FILTER_FLAG_STRIP_HIGHStrips characters that have a numerical value >127.
FILTER_FLAG_ALLOW_FRACTIONAllows a period (.) as a fractional separator in numbers.
5
FILTER_FLAG_ALLOW_THOUSANDAllows a comma (,) as a thousands separator in numbers.
6
FILTER_FLAG_ALLOW_SCIENTIFICAllows an e or E for scientific notation in numbers.
7
FILTER_FLAG_NO_ENCODE_QUOTESIf this flag is present, single (‘) and double (“) quotes will not be encoded.
8
FILTER_FLAG_ENCODE_LOWEncodes all characters with a numerical value <32.
9
FILTER_FLAG_ENCODE_HIGHEncodes all characters with a numerical value >127.
10
FILTER_FLAG_ENCODE_AMPEncodes ampersands (&).
11
FILTER_NULL_ON_FAILUREReturns null for unrecognized values.
12
FILTER_FLAG_ALLOW_OCTALRegards inputs starting with a zero (0) as octal numbers.
13
FILTER_FLAG_ALLOW_HEXRegards inputs starting with 0x or 0X as hexadecimal numbers.
14
FILTER_FLAG_EMAIL_UNICODEAllows the local part of the email address to contain Unicode characters.
15
FILTER_FLAG_IPV4Allows the IP address to be in IPv4 format.
16
FILTER_FLAG_IPV6Allows the IP address to be in IPv6 format.
17
FILTER_FLAG_NO_PRIV_RANGEFails validation for the following private IPv4 ranges: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16.
18
FILTER_FLAG_NO_RES_RANGEFails validation for the following reserved IPv4 ranges: 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 and 240.0.0.0/4.Fails validation for the following reserved IPv6 ranges: ::1/128, ::/128, ::ffff:0:0/96 and fe80::/10.
19
FILTER_FLAG_GLOBAL_RANGEFails validation for non global IPv4/IPv6 ranges
20
FILTER_FLAG_SCHEME_REQUIREDRequires the URL to contain a scheme part.
21
FILTER_FLAG_HOST_REQUIREDRequires the URL to contain a host part.
22
FILTER_FLAG_PATH_REQUIREDRequires the URL to contain a path part.
23
FILTER_FLAG_QUERY_REQUIREDRequires the URL to contain a query string.
24
FILTER_REQUIRE_SCALARRequires the value to be scalar.
25
FILTER_REQUIRE_ARRAYRequires the value to be an array.
26
FILTER_FORCE_ARRAYIf the value is a scalar, it is treated as array with the scalar value as only element.
Filter Functions
The filter extension includes the following filter functions −
Sr.No
ID & Description
1
filter_has_var()Checks if variable of specified type exists
2
filter_id()Returns the filter ID belonging to a named filter
3
filter_input_array()Gets external variables and optionally filters them
4
filter_input ()Gets a specific external variable by name and filters it
5
filter_list()Returns a list of all supported filters
6
filter_var_array()Gets multiple variables and optionally filters them
7
filter_var()Filters a variable with a specified filter
Predefined Constants
The above functions use one parameter called input_type which is one of the predefined enumerated constants representing how the input has been provided to the PHP script for filtering purpose.
Constant
Types
INPUT_POST (int)
POST Variables
INPUT_GET (int)
GET Variables
INPUT_COOKIE (int)
COOKIE Variables
INPUT_ENV (int)
ENV Variables
INPUT_SERVER (int)
SERVER Variables
INPUT_SESSION (int)
SESSION Variables
INPUT_REQUEST (int)
REQUEST Variables
filter_has_var() function
The filter_has_var() function checks if variable of specified type exists.
The input_type is one of predefined constants INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV; where as the var_name parameter is the name of a variable to check. The function returns true on success or false on failure.
Example
Visit the following PHP script on the XAMPP server.
The type parameter is one of the constants INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV. Second parameter is var_name, the name of a variable to get. You can use the filter to be applied. Use any of the predefined filter flags. If omitted, FILTER_DEFAULT will be used
The function returns the value of the requested variable on success, false if the filter fails, or null if the var_name variable is not set.
Example
Take a look at the following example −
<?php
if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)) {
This function is useful for retrieving many values without repetitively calling filter_input().
The type parameter is one of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.
The options parameter is an array defining the arguments. A valid key is a string containing a variable name and a valid value is either a filter type, or an array optionally specifying the filter, flags and options. This parameter can be also an integer holding a filter constant. Then all values in the input array are filtered by this filter.
The function returns an array containing the values of the requested variables on success. If the input array designated by type is not populated, the function returns null if the FILTER_NULL_ON_FAILURE flag is not given, or false otherwise. For other failures, false is returned.
Example
To include an array in the HTTP request, we use the following HTML form in “hello.html”, and send it by POST method.
<!DOCTYPE html><html><body><h1>Filter Input Array</h1><form action="hello.php" method="POST"><p><label for="email">Enter your email:</label><input type="text" id="email" name="email"></p><p><label for="age">Enter your age<label><input type = "text" id="age" name="age"></p><input type="submit"></form></body></html>
The PHP script to validate the input array is as follows −
In the theory of software engineering, the term “Design patterns” generally refers to a reusable solution that can be used as a template for developing applications to address commonly occurring problems. You can consider the software design patterns as formalized best practices when developing software solutions.
Most of the standard design patterns can be very effectively implemented in developing applications in PHP. In this chapter, we shall learn how to apply some of the popular design patterns in developing PHP applications.
Singleton Pattern
The singleton design pattern is useful when you want to restrict the instantiation of an object of a certain class to only one instance. The name “singleton pattern” comes from the concept of singleton in Mathematics. Singleton pattern ensures that there will be only one instance, having a global access to it throughout the application.
Typical application of singleton pattern is creation of a database connection object, which must be created once in the lifetime of an application.
Example
In the following code, the DataBaseConnector class can be instantiated only once, otherwise a message that disallows duplicate object will be issued.
<?php
class DataBaseConnector {
private static $obj;
private final function __construct() {
echo __CLASS__ . " object created for first time ". PHP_EOL;
}
public static function getConnect() {
if (!isset(self::$obj)) {
self::$obj = new DataBaseConnector();
return self::$obj;
} else {
echo "connection object could not be created again" . PHP_EOL;
}
}
DataBaseConnector object created for first time
connection object could not be created again
bool(false)
Factory Pattern
This is one of the most commonly used design patterns. In this pattern, you dont declare the object of the desired class directly, but another class is provided whose static method creates the required object.
Example
The following example demonstrates how factory design pattern works −
<?php
class Automobile {
private $bikeMake;
private $bikeModel;
public function __construct($make, $model) {
$this->bikeMake = $make;
$this->bikeModel = $model;
}
public function getMakeAndModel() {
return $this->bikeMake . ' ' . $this->bikeModel;
}
}
class AutomobileFactory {
public static function create($make, $model) {
return new Automobile($make, $model);
}
The strategy pattern recommends an approach where you encapsulate specific families of algorithms allowing the client class responsible for instantiating a particular algorithm. The class that implements the pattern has no knowledge of the actual implementation.
Example
Here is a code that demonstrates the use of strategy pattern. We have an interface whose case() method is implemented differently by two different classes. The object of testdata class calls the respective case() methods indirectly through its own process() method.
<?php
interface example {
public function case($str);
}
class ucase implements example {
public function case($str) {
return strtoupper($str);
}
}
class lcase implements example {
public function case($str) {
return strtolower($str);
}
}
class testdata {
private $data;
public function __construct($input) {
$this->data = $input;
}
public function process(example $type) {
return $this->data = $type->case($this->data);
}
MVC, which stands for Model, View and Controller, is a very popular softeware architecture pattern. Most of the PHP networks such as Laravel, Symfony etc. implement the MVC architecture.
The separation of the role of each layer in an application is as follows −
Model − Refers to the data structure. In this case, the database.
View − Refers to the user interface. The HTML and CSS.
Controller − The “middleman” doing the processing. Accepts input from the view, and works with the model. Self-explanatory, the PHP scripts and libraries themselves.
The View acts as the GUI, the Model acts as the back-end and the Control acts as an adapter. Here, three parts are interconnected with each other. It will pass the data and access the data between each other.
Example
Let us implement the MVC design pattern in pure PHP, JavaScript and HTML in the example below −
The presentation layer of the application is view.php, which renders a HTML form. The user submits the data to a controller script. The result returned by the controller is rendered on the web page with a bit of JavaScript
The controller script requires model.php, and uses the database object, calls the select method to fetch data from the database. The result is stored in the current session so that it can be accessed on the view page.
PHP is by far the most popular server-side programming language for web application development, with nearly 75% of websites using PHP either in its core form or one of the PHP frameworks available. To make a choice between using “core PHP” or frameworks for web development, we need to understand the pros and cons of both.
To give a simple analogy, developing a web application purely with core PHP is like solving a mathematical problem manually by writing down each step on the paper. On the other hand, using a framework is similar to using tools such as a calculator to solve a problem. Just as a calculator, the frameworks are useful tools for rapid application development.
Core PHP vs Frameworks Pros and Cons
A web framework, especially a PHP framework is a collection of one or more PHP libraries and classes. It provides a generic functionality that allows the developer to concentrate more on the application logic, rather than writing code scratch. It provides a reusable software environment that quickly builds a minimal working template application.
Developing a web application purely in core PHP has its own advantages and disadvantages −
It gives the developer better control and flexibility.
At the same time, for a larger application developed with core PHP only can become unwieldy, difficult to manage and maintain.
Now, let’s turn to pros and cons of using PHP Frameworks −
A PHP framework such as Symfony, Laravel or Yii offers a more standardized approach towards web application development. With most of the routine and repetitive part handled by the framework, the developer can concentrate more on the application logic. Hence, there is lesser time wasted in debugging.
On the other hand, a framework is not as flexible compared to core PHP. The skeleton template of the application is readily made available by the framework, leaving the developer to customize the functionality only within the scope defined by the framework.
The MVC Architecture
Most of the web application frameworks employ the MVC (Model, View and Controller) architecture, which makes it a lot easier to write quality, robust code, by separating the logic from the style.
If you wish to use the core PHP features for your application development, you are free to adopt an object oriented approach or a modular approach, whichever suits you.
Built-in Security Measures
PHP frameworks offer built-in security measures to be incorporated in a web applications.
If you choose to develop an application with core PHP, you will have to provide the security measures explicitly.
Most of the frameworks however have a few external dependencies, which may leave the application rather vulnerable, as compared to a core PHP application which is a self-contained solution.
A framework-based application may be a little slow when it comes to performance, as compared to core PHP application, especially for a smaller application.
Comparison: Core PHP vs Frameworks
The comparison between the two can be summarized as follows −
For smaller applications, core PHP is preferrable over framework.
Framework offers rapid development and code reusability.
Frameworks are less flexible.
Using core PHP features, the developer has complete control.
For large applications, the MVC architecture is helpful.
Frameworks offer integrated authorization and authentication support. In a core PHP application, the security rules need to be explicitly defined.
The PHP ecosystem has a number of web frameworks. Some of the popular PHP web frameworks are Laravel, Yii, CakePHP etc. While one can build a web application with the help of core PHP, developers are increasingly preferring web frameworks for rapid application development.
What are Software Frameworks?
In computer programming, a software framework is a collection of libraries and classes that provide a generic functionality that allows the developer to concentrate more on the application logic, rather than writing code for routine but tedious low-level processes.
A framework provides a reusable software environment that quickly builds a minimal working template application. Developer can then modify these blocks for additional functionality.
Each framework is built to help the developer build an application of a certain type. For example, web frameworks (sometimes also called “web application framework”) are used for the development of web applications including web services, web resources, and web APIs.
In this chapter, let us take a brief overview of some of the popular PHP frmeworks.
FuelPHP
FuelPHP (https://fuelphp.com/) works based on Model View Control and having innovative plug ins. FuelPHP supports router-based theory where you might route directly to a nearer the input uri, making the closure the controller and giving it control of further execution.
CakePHP
CakePHP (https://cakephp.org/) is a great source to build up simple and great web application in an easy way. Some great features which are inbuilt in PHP are input validation, SQL injection prevention that keeps you application safe and secure.
FlightPHP
FlightPHP (https://flightphp.com/) is very helpful to make RESTful web services and it is under MIT licence.
Symfony
Symfony is for highly professional developers to build websites with PHP components such as Drupal, PHPBB, laravel, eX, OROCRM and piwik.
yiiFramework
YiiFramework (https://www.yiiframework.com/) works based on web 2.0 with high end security. It included input Validation, output filtering, and SQL injection.
Laravel
Laravel (https://laravel.com/) is most useful for RESRful Routing and light weight bled tempting engine. Laravel has integrated with some of great components of well tested and reliable code.
Zend
Zend (https://framework.zend.com/) is Modern frame work for performing high end web applications. This works based on Cryptographic and secure coding tools. Zend Framework is a collection of professional PHP packages with more than 570 million installations.
It can be used to develop web applications and services using PHP 5.6+, and provides 100% object-oriented code using a broad spectrum of language features.
Codeigniter
Codeigiter is simple to develop small footprint for developer who need simple and elegant tool kit to create innovative web applications.
Phalcon PHP
Pholcon (https://phalcon.io/en-us) is a PHP framework that works based on MVC and integrated with innovative architecture to do perform faster.
PHPixie
PHPixie (https://phpixie.com/) works based on MVC and designed for fast and reliability to develop web sites.
Agavi
Agavi is a powerful and scalable PHP5 application framework and it follows the MVC model. Agavi can help PHP developers in writing clean and maintainable code.
PERL is a dynamically typed, high level and general-purpose programming language. It is normally believed that PERL is an acronym for Practical Extraction and Reporting Language. PHP on the other hand is also a general-purpose scripting language. Initially PHP used to be a short for Personal Home Page, but these days it has now been recognized as a recursive acronym PHP: Hypertext Preprocessor.
In this chapter, certain major similarities and differences in between PHP and PERL are listed. This will help PERL developers to understand PHP very quickly and avoid common mistakes.
Similarities between PERL and PHP
Both Perl and PHP are scripting languages. They are not used to build native standalone executables in advance of execution.
Early versions of PHP were inspired by PERL. PHP’s basic syntax is very similar to PERL. Both share a lot of syntactic features with C. Their code is insensitive to whitespace, Each statement is terminated by semicolons.
Both PHP and PERL use curly braces to organize multiple statements into a single block. Function calls start with the name of the function, followed by the actual arguments enclosed in parentheses and separated by commas, in both the cases.
All variables in PHP look like scalar variables in PERL: a name with a dollar sign ($) in front of it.
Since both the languages are dynamically typed, you dont need to declare the type of a PHP as well as a PERL variable before using it.
In PHP, as in PERL, variables have no intrinsic type other than the value they currently hold. You can store either number or string in same type of variable.
Both PHP and Perl do more interpretation of double-quoted strings (“string”) than of single-quoted strings (‘string’).
Differences between PERL and PHP
PHP can be embedded inside HTML. Although it is possible to run a PHP script from the command line, it is more popularly used as a server-side scripting language on a Web server and used for producing Web pages.
If you are used to writing CGI scripts in PERL, the main difference in PHP is that you no longer need to explicitly print large blocks of static HTML using print or heredoc statements and instead can simply write the HTML itself outside of the PHP code block.
No @ or % variables − PHP has one only kind of variable, which starts with a dollar sign ($). Any of the datatypes in the language can be stored in such variables, whether scalar or compound. In PERL, the array variable is prefixed with @ symbol. Also, the hash variable is prefixed by % symbol.
Unlike PERL, PHP has a single datatype called an array which can be an indexed array or associative array, which is similar to hash in PERL.
Function calls in PHP look pretty much like subroutine calls in PERL. Function definitions in PHP, on the other hand, typically require some kind of list of formal arguments as in C or Java which is not the case in PERL.
Scope of variables in PERL is global by default. This means that top-level variables are visible inside subroutines. Often, this leads to promiscuous use of globals across functions. In PHP, the scope of variables within function definitions is local by default.
No module system in PHP as such. In PHP there is no real distinction between normal code files and code files used as imported libraries.
Break and continue rather than next and last PHP is more like C language and uses break and continue instead of next and last statement as in PERL.
No elsif − A minor spelling difference: Perl’s elsif is PHP’s elseif.
In addition to Perl-style (#) single-line comments, PHP offers C-style multiline comments (/* comment */) and Java-style single-line comments (// comment).
Regular expressions − PHP does not have a built-in syntax specific to regular expressions, but has most of the same functionality in its “Perl-compatible” regular expression functions.
If you have a prior knowledge of C programming, learning PHP becomes a lot easier, especially the basics. Although PHP is a lot like C, it is bundled with a whole lot of Web-specific libraries, with everything hooked up directly to your favorite Web server.
The simplest way to think of PHP is as interpreted C that you can embed in HTML documents. PHP script can also be executed from the command line, much like a C program.
The syntax of statements and function definitions should be familiar, except that variables are always preceded by $, and functions do not require separate prototypes.
Let us take a look at some of the similarities and differences in PHP and C −
Similarities Between C and PHP
Syntax − Broadly speaking, PHP syntax is the same as in C, which is what makes learning PHP easier, if you are already conversant with C.
Similar to C, PHP Code is blank insensitive, statements are terminated with semicolons.
Curly brackets are used to put multiple statements into blocks.
PHP supports C and C++-style comments (/* */ as well as //), and also Perl and shell-script style (#).
Operators − The assignment operators (=, +=, *=, and so on), the Boolean operators (&&, ||, !), the comparison operators (<,>, <=, >=, ==, !=), and the basic arithmetic operators (+, -, *, /, %) all behave in PHP as they do in C.
Control Structures − The basic control structures (if, switch, while, for) behave as they do in C, including supporting break and continue. One notable difference is that switch in PHP can accept strings as case identifiers.
PHP also has foreach looping construct that traverses the collections such as arrays.
Function Names − As you peruse the documentation, you.ll see many function names that seem identical to C functions.
Differences Between C and PHP
Dollar Sign − All variable names are prefixed with a leading $. Variables do not need to be declared in advance of assignment, and they have no intrinsic type. PHP is a dynamically typed language, as against C being a statically typed language.
Types − PHP has only two numerical types: integer (corresponding to a long in C) and double (corresponding to a double in C). In PHP, float is synonymous to double. Strings are of arbitrary length. There is no separate char type in PHP, as is the case in C.
Type Conversion − C is a strongly typed language, as type of a variable must be declared before using, and the types are checked at compile time. PHP on the other hand, is a weakly typed language, types are not checked at compile time, and type errors do not typically occur at runtime either. Instead, variables and values are automatically converted across types as needed.
Arrays − Arrays have a syntax superficially similar to C’s array syntax, but they are implemented completely differently. In C, an array is a collection of similar data types. In a PHP array, the items may be of different types. PHP arrays are actually associative arrays or hashes, and the index can be either a number or a string. They do not need to be declared or allocated in advance.
No Struct Type − The struct keyword in C is used to define a new data type. There is no struct keyword or its equivalent in PHP, partly because the array and object types together make it unnecessary. The elements of a PHP array need not be of a consistent type.
No Pointers − Pointers are an important concept in C. There are no pointers available in PHP, although the tapeless variables play a similar role. Unlike C, PHP does support variable references. You can also emulate function pointers to some extent, in that function names can be stored in variables and called by using the variable rather than a literal name.
No Prototypes − Functions do not need to be declared before their implementation is defined, as long as the definition can be found somewhere in the current code file or included files. On the contrary, a C function must defined before it is used.
No main() − In a C program, the main() function is the entry point, irrespective of where it is present in the code. A PHP program on the other hand starts execution from the first statement in the script
Memory Management − The PHP engine is effectively a garbage-collected environment (reference-counted), and in small scripts there is no need to do any deallocation. You should freely allocate new structures – such as new strings and object instances. IN PHP5, it is possible to define destructor for objects, but there is are no free or delete keywords as in C/C++. Destructor are called when the last reference to an object goes away, before the memory is reclaimed.
Compilation and Linking − PHP is an interpreted language. Hence, the compiled version of PHP script is not created. A C program is first compiled to obtain the object code, which is then linked to the required libraries to build an executable. There is no separate compilation step for PHP scripts. A PHP script cannot be turned into a self executable.
Permissiveness − As a general matter, PHP is more forgiving than C (especially in its type system) and so will let you get away with new kinds of mistakes. Unexpected results are more common than errors.
A bug in a PHP code refers to an error in the program that leads to unexpected results or crash. A systematic approach towards the process of finding bugs before users do is called debugging. In this chapter, some important tips to trace bugs in a PHP code are given.
Programs rarely work correctly the first time. Many things can go wrong in your program that can cause the PHP interpreter to generate an error message. You have a choice about where those error messages go. The messages can be sent along with other program output to the web browser. They can also be included in the “web server error log”.
To make error messages display in the browser, set the “display_errors” configuration directive to ON. Ensure that the following settings are enabled in the “php.ini” file.
display_errors=On
display_startup_errors=On
You can also use the ini_set() function to override the “pnp.ini” configuration −
To send errors to the web server error log, set “log_errors” to ON. You can set them both to On if you want error messages in both places.
PHP defines some constants that you can use to set the value of error_reporting such that only errors of certain types get reported −
E_ALL (for all errors except strict notices)
E_PARSE (parse errors)
E_ERROR (fatal errors)
E_WARNING (warnings)
E_NOTICE (notices)
E_STRICT (strict notices)
While writing your PHP program, it is a good idea to use PHP-aware editors like BBEdit or Emacs. One of the special features of these editors is syntax highlighting. It changes the color of different parts of your program based on what those parts are. For example, strings are pink, keywords such as if and while are blue, comments are grey, and variables are black.
VS Code from Microsoft is also a good choice for editing PHP code. If you install VS Code extension Intelephense, you will get type hints and error message as you enter PHP statements in the editor window.
Another feature is quote and bracket matching, which helps to make sure that your quotes and brackets are balanced. When you type a closing delimiter such as “}”, the editor highlights the opening “{” that it matches.
Points to Check while Debugging a Code
One needs to verfity the following points while debugging a program code −
Missing Semicolons
Every PHP statement ends with a semicolon (;). PHP doesn’t stop reading a statement until it reaches a semicolon. If you leave out the semicolon at the end of a line, PHP continues reading the statement on the following line.
Not Enough Equal Signs
When you ask whether two values are equal in a comparison statement, you need two equal signs (==). Using one equal sign is a common mistake.
Misspelled Variable Names
If you misspelled a variable then PHP understands it as a new variable. Remember: To PHP, $test is not the same variable as $Test.
Missing Dollar Signs
A missing dollar sign in a variable name is really hard to see, but at least it usually results in an error message so that you know where to look for the problem.
Troubling Quotes
You can have too many, too few, or the wrong kind of quotes. So check for a balanced number of quotes.
Missing Parentheses and curly brackets
They should always be in pairs.
Array Index
An array in PHP is a collection of items, each item assigned an incrementing index starting with 0.
Moreover, handle all the errors properly and direct all trace messages into system log file so that if any problem happens then it will be logged into system log file and you will be able to debug that problem.