PHP Unit 2
Object oriented Programming with PHP and Error Handling
Data Abstraction and Data Encapsulation in PHP
In PHP, data abstraction and data encapsulation are two important concepts in object-oriented programming.
Data Abstraction
Data abstraction is a technique that allows you to hide the complexity of your code and only expose the essential features to the users. In PHP, you can achieve data abstraction using abstract classes and interfaces.
An abstract class is a class that cannot be instantiated and is used as a base class for other classes. It contains abstract methods, which are defined but not implemented in the abstract class. The abstract methods must be implemented in the subclasses that inherit from the abstract class.
An interface is a collection of abstract methods that define a contract for the classes that implement it. An interface does not contain any implementation code, only method signatures.
Abstract Class Example
abstract class Shape {
protected $color;
public function __construct($color) {
$this->color = $color;
}
abstract protected function getArea();
}
class Circle extends Shape {
protected $radius;
public function __construct($color, $radius) {
parent::__construct($color);
$this->radius = $radius;
}
protected function getArea() {
return pow($this->radius, 2) * pi();
}
}
In this example, Shape is an abstract class with a constructor that sets the protected variable $color. It also contains an abstract method getArea() that is not implemented in the Shape class but must be implemented in any subclasses that inherit from the Shape class.
Circle is a subclass of Shape that has a constructor that calls the parent constructor and sets the protected variable $radius. Circle implements the getArea() method, which calculates the area of a circle based on the radius.
Interface Example
interface Shape {
public function getArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function getArea() {
return pow($this->radius, 2) * pi();
}
}
In this example, Shape is an interface that defines the method getArea(). Circle is a class that implements the Shape interface and provides an implementation of the getArea() method.
Data Encapsulation
Data encapsulation is a technique that allows you to hide the internal details of your code and only expose the necessary data and methods to the users. In PHP, you can achieve data encapsulation using access modifiers.
There are three access modifiers in PHP:
- public: The public keyword allows the data and methods to be accessed from anywhere, both inside and outside the class.
- private: The private keyword restricts the data and methods to be accessed only from within the class.
- protected: The protected keyword allows the data and methods to be accessed from within the class and its subclasses.
By using access modifiers, you can control the visibility of your data and methods and prevent unwanted access or modification.
In conclusion, data abstraction and data encapsulation are important concepts in object-oriented programming that allow you to write more maintainable, reusable, and secure code in PHP.
Here's an example code in PHP that demonstrates data encapsulation:
class BankAccount {
private $accountNumber;
private $balance;
public function __construct($accountNumber, $balance) {
$this->accountNumber = $accountNumber;
$this->balance = $balance;
}
public function deposit($amount) {
$this->balance += $amount;
}
public function withdraw($amount) {
if ($this->balance >= $amount) {
$this->balance -= $amount;
} else {
echo "Insufficient funds";
}
}
}
In this example, the BankAccount class has private variables $accountNumber and $balance. The constructor method sets the values of these variables when a new instance of the class is created.
The class also has public methods deposit() and withdraw() for depositing and withdrawing money from the account. These methods allow interaction with the private variables $accountNumber and $balance, while ensuring that unauthorized access or modification is prevented.
Polymorphism in PHP.
Polymorphism in PHP refers to the ability to use a single interface to represent different types of objects. This allows you to write code that can work with objects of different classes, as long as they implement the same interface or inherit from the same parent class.
For example, suppose you have an interface Shape with a method getArea(). You can create different classes that implement the Shape interface, such as Circle, Square, and Triangle. Then you can write code that works with objects of any of these classes, as long as they implement the getArea() method.
File and File system Function.
Sure, here are some examples of how to use the file functions in PHP:
fopen():
$file = fopen("example.txt", "r");
This code opens the file example.txt in read-only mode and returns a file pointer resource that can be used to read from the file.
fclose():
fclose($file);
This code closes the file that was opened using the fopen() function. The file pointer resource returned by fopen() is passed as a parameter to fclose().
fread():
$file = fopen("example.txt", "r");
$data = fread($file, filesize("example.txt"));
fclose($file);
This code opens the file example.txt in read-only mode, reads the entire contents of the file into the variable $data, and then closes the file.
fwrite():
$file = fopen("example.txt", "w");
fwrite($file, "This is some sample text.");
fclose($file);
This code opens the file example.txt in write mode, writes the string "This is some sample text." to the file, and then closes the file.
feof():
$file = fopen("example.txt", "r");
while(!feof($file)) {
echo fgets($file) . "
";
}
fclose($file);
This code opens the file example.txt in read-only mode, reads each line of the file using the fgets() function, and then checks for the end of the file using the feof() function.
file():
$data = file("example.txt");
foreach($data as $line) {
echo $line . "
";
}
This code reads the entire contents of the file example.txt into an array using the file() function, and then loops through each element of the array and outputs it to the browser.
PHP Open File Mode
Here is a table showing the different modes that can be used with the fopen() function in PHP:
| Mode | Description |
|---|---|
| r | Read only. Starts at the beginning of the file. |
| r+ | Read/write. Starts at the beginning of the file. |
| w | Write only. Opens and truncates the file; or creates a new file if it doesn't exist. |
| w+ | Read/write. Opens and truncates the file; or creates a new file if it doesn't exist. |
| a | Write only. Opens and writes to the end of the file; or creates a new file if it doesn't exist. |
| a+ | Read/write. Preserves file content by writing to the end of the file; or creates a new file if it doesn't exist. |
| x | Write only. Creates a new file. Returns FALSE and an error if file already exists. |
| x+ | Read/write. Creates a new file. Returns FALSE and an error if file already exists. |
File System Functions:
PHP also provides a number of file system functions that allow you to perform operations on files and directories. Here are some of the most commonly used file system functions:
mkdir(): Creates a new directory.
rmdir(): Deletes an existing directory.
rename(): Renames a file or directory.
file_exists(): Checks if a file exists.
is_file(): Checks if a file is a regular file.
is_dir(): Checks if a file is a directory.
scandir():
Returns an array of files and directories in a directory
Session in PHP
Session variables are used to store information about a user across multiple pages. You can create a session variable in PHP using the session_start() function and then setting a value to a session variable using the $_SESSION superglobal. For example:
<?php
session_start();
$_SESSION['username'] = 'JohnDoe';
?>
This code starts a session and sets the value of the username session variable to JohnDoe. You can then access the session variable on other pages using the same $_SESSION superglobal.
PHP Cookie
PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user.
Cookie is created at server side and saved to client browser. Each time when client sends request to the server, cookie is embedded with request. Such way, cookie can be received at the server side.

In short, cookie can be created, sent and received at server end.
PHP setcookie() function
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can access it by $_COOKIEsuperglobal variable.
Example
setcookie("CookieName", "CookieValue");/* defining name and value only*/
setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1*60*60 seco ds or 3600 seconds)
setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "mydomain.com", 1);
PHP $_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.
Example
$value=$_COOKIE["CookieName"]; //returns cookie value
PHP Cookie Example
<?php
setcookie("user", "Naruto");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>
Output:
Sorry, cookie is not found!
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:
Cookie Value: Naruto
PHP Delete Cookie
If you set the expiration date in past, cookie will be deleted.
<?php
setcookie("CookieName", "", time() - 3600);// set the expiration date to one hour ago
?>
Error Handling and Debugging in PHP
Types of errors in PHP
An error is a mistake in a program that may be caused by writing incorrect syntax or incorrect code. An error message is displayed on your browser containing the filename along with location, a message describing the error, and the line number in which the error has occurred.
There are usually different types of errors. In PHP, mainly four types of errors are considered:
- Syntax Error or Parse Error
- Fatal Error
- Warning Error
- Notice Error
We will discuss all these errors in detail with examples:
Syntax Error or Parse Error
A syntax error is a mistake in the syntax of source code, which can be made by programmers due to their lack of concern or knowledge. It is also known as Parse error. The compiler is used to catch the syntax error at compile time.
Example 1: Missing semicolon
<?php
echo "Bob: I'm Bob. How are you?"
?>
Output
Parse error: syntax error, unexpected 'echo' (T_ECHO), expecting ',' or ';' in C:\\xampp\\htdocs\\program\\fatalerror.php on line 2
Explanation: In this above example, a semicolon (;) was missing in line 5. So, it generated a parse error and displayed an error message on the browser as given in the output.
Example 2: Missing dollar symbol
<?php
/*------------------syntax error-------------------*/
car = "Tesla";
echo car;
Output
Parse error: syntax error, unexpected '=' in C:\\xampp\\htdocs\\program\\fatalerror.php on line 5
Explanation: In this above example, the dollar ($) symbol was missing in line 5. So, it generated a parse error and displayed an error message on the browser as given in the output.
Fatal Error
- A fatal error is another type of error, which is caused by the use of an undefined function.
- The PHP compiler understands the PHP code but also recognizes the undefined function.
- This means that when a function is called without providing its definition, the PHP compiler generates a fatal error.
A fatal error is generated when a function is called without its definition. See the below example containing the fatal error -
Example: Calling undefined function
<?php
/*------------------fatal error-------------------*/
function add($f1, $f2) {
$sum = $f1 + $f2;
echo "Addition:" . $sum;
}
$f1 = 23;
$f2 = 56;
//call the function that is not defined
//generate fatal error
catch_fatal_error();
//echo "Fatal Error";
?>
In the above code, we have defined the add() function but called another function, which is catch_fatal_error(). Therefore, it generates a fatal error and prints an error message on the browser as given below:
Output
Fatal error: Uncaught Error: Call to undefined function catch_fatal_error() in C:\\xampp\\htdocs\\program\\fatalerror.php:15 Stack trace: #0 {main} thrown in C:\\xampp\\htdocs\\program\\fatalerror.php on line 13
Warning Error
A warning is generated when the programmer tries to include a missing file. The PHP function calls that missing file, which does not exist. The warning error does not stop/prevent the execution of the program.
The main reason behind generating a warning error is to pass an incorrect number of parameters to a function or to include a missing file.
Example: Include missing file
<?php
$name = 'Naruto';
echo "Warning Error: ";
//include a file in the code
include('ninja.php');
?>
Output
``Warning Error: Warning: include(ninja.php): failed to open stream: No such file or directory in C:\xampp\htdocs\program\fatalerror.php on line 7`
`Warning: include(): Failed opening 'jtp.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\program\fatalerror.php on line 7``
Explanation: In this example, we tried to include a file in our program, which does not exist. So, it generated a warning and displayed an error message.
Notice Error
A notice error is the same as a warning error. When the program contains something wrong, the notice error occurs. But it allows/continues the execution of the program with a notice error. Notice error does not prevent the execution of the code. For example - access to an undefined variable.
Generally, a notice error occurs when we try to use or access a variable that is undefined. See the below example to understand it-
Example 2: Access undefined variable
<?php
/*------------------notice error-------------------*/
$telecom = "Airtel";
echo $telecom;
echo $automobile;
?>
Output
Airtel Notice: Undefined variable: automobile in C:\\xampp\\htdocs\\program\\fatalerror.php on line 6
Explanation: In this above example, we were trying to use a variable $automobile, which was not defined. Therefore, it generated a notice "Undefined variable" and continued the execution of the program.
Displaying PHP errors
To display PHP errors on a web page, you can use the error_reporting() and ini_set() functions. Here's an example:
error_reporting(E_ALL);
ini_set('display_errors', 1);
This code sets the error reporting level to show all types of errors, and enables the display of errors on the web page. This is useful for debugging your code during development, but should be disabled in production environments to prevent sensitive information from being exposed to users.
Example :
Another option is to log errors to a file instead of displaying them on the web page. This can be done using the error_log() function. Here's an example:
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', '/var/log/php_errors.log');
This code sets the error reporting level to show all types of errors, and enables logging of errors to the file /var/log/php_errors.log. This is a more secure way to handle errors in production environments, as it keeps sensitive information hidden from users but still allows you to debug your code if necessary.
Adjusting Error Reporting.
- To adjust error reporting in PHP, you can use the
error_reporting()function to set the level of errors that are reported. - The possible error levels are
E_ALL,E_ERROR,E_WARNING,E_PARSE,E_NOTICE,E_CORE_ERROR,E_CORE_WARNING,E_COMPILE_ERROR,E_COMPILE_WARNING,E_USER_ERROR,E_USER_WARNING,E_USER_NOTICE, andE_STRICT. - You can also use the
ini_set()function to adjust thedisplay_errorsandlog_errorssettings to control whether errors are displayed on the screen or logged to a file.
📌 Creating Custom error handler
What is an Exception?
An exception is an object that describes an error or unexpected behaviour of a PHP script.
Exceptions are thrown by many PHP functions and classes.
User defined functions and classes can also throw exceptions.
Exceptions are a good way to stop a function when it comes across data that it cannot use.
Throwing an Exception
The throw statement allows a user defined function or method to throw an exception. When an exception is thrown, the code following it will not be executed.
If an exception is not caught, a fatal error will occur with an "Uncaught Exception" message.
The try...catch Statement
To avoid the error from the example above, we can use the try...catch statement to catch exceptions and continue the process.
Syntax
try {
// code that can throw exceptions
} catch(Exception $e) {
// code that runs when an exception is caught
}
Example
Show a message when an exception is thrown:
<?php
$n = 10;
$m = 2;
try {
if ($m == 0) {
throw new Exception("Division by zero.");
}
echo $n / $m;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
PHP debugging techniques
Here are some common debugging techniques in PHP:
- Print statements: You can use
echoorvar_dumpstatements to print the value of a variable or the output of a function. This can help you see what's going on in your code and identify where errors are occurring. - Debugging tools: PHP has a number of debugging tools that you can use to step through your code, set breakpoints, and inspect variables at runtime. Some popular PHP debugging tools include Xdebug, Zend Debugger, and PHP Debug Bar.
- Error reporting: As mentioned earlier, you can adjust the error reporting level in PHP to show different types of errors. This can help you identify errors that may be occurring in your code.
- Logging: You can use logging to record information about your code as it runs. This can be useful for debugging and troubleshooting issues that may be occurring in your code.
- Unit testing: Unit testing involves creating automated tests that verify the behavior of individual components of your code. This can help you catch errors early and ensure that your code is working as expected.
By using these techniques, you can identify and fix errors in your PHP code and create more reliable and robust applications.