Oop (Unit 4)
Oop (Unit 4)
In object-oriented programming (OOP), classes and objects are fundamental concepts that
allow you to model and organize your code in a more modular and reusable way. Let‟s break
down these concepts in the context of PHP, using simple language and a real-time example.
Class:
A class is like a blueprint or a template that defines a type of object. It encapsulates the
properties (attributes) and behaviors (methods) that objects of that type will have. In PHP, you
<?php
class Dog {
public $name;
public $breed;
In this example, we‟ve created a Dog class with properties ($name and $breed) and methods
An object is an instance of a class. It‟s a concrete realization of the blueprint defined by the
class. You can create multiple objects from the same class, each with its own set of property
values.
<?php
// Creating objects from the Dog class
$dog1 = new Dog();
$dog2 = new Dog();
$dog2->name = "Max";
$dog2->breed = "Golden Retriever";
// Calling methods
$dog1->bark(); // Outputs: Woof! Woof!
$dog2->fetch(); // Outputs: Max is fetching.
?>
In this example, we‟ve created two instances ($dog1 and $dog2) of the Dog class. Each object
has its own set of properties and can invoke the methods defined in the class.
The Four pillars of OOPs are abstraction, encapsulation, inheritance, and polymorphism.
Abstraction:
complex implementation details of an object and exposing only the essential features or
functionalities. It allows you to focus on what an object does rather than how it achieves its
triangles. Each shape has an area, but the way you calculate the area for each shape is
different.
shapes, which is the calculation of the area. The Circle and Rectangle classes are concrete
classes that inherit from the Shape class and provide their specific implementations for
Encapsulation:
polymorphism, and abstraction. Encapsulation refers to the bundling of data and the methods
that operate on that data into a single unit, often called a class. The main idea is to hide the
internal details of how an object works and expose only what is necessary for the outside
class Car {
// Private properties (attributes)
private $model;
private $color;
private $fuelLevel;
$myCar->drive();
In this example:
The Car class encapsulates the internal details (model, color, and fuel level) by
The internal details are hidden from external code, and access is controlled through
Inheritance:
Inheritance is a concept where a new class (called the child or subclass) can inherit attributes
and behaviors (properties and methods) from an existing class (called the parent or
In this example, we have a parent class Animal with a property $name and a method eat().
The Dog and Cat classes are child classes that inherit from the Animal class. They not only
inherit the property and method from Animal but can also have their own unique methods
The different types of errors including error logs, error handling, error handling functions,
and other error PHP framework error handling. Let‟s start by defining the difference between
the terms “error” and “exception” and other common terms in PHP.
Many use error handling and exception handling interchangeably. When we say error
handling we are referring to the process of catching errors produced by your program which
needs proper action. Since PHP came into a new object-oriented (OOP) way of dealing with
errors, exception handling was introduced. It is used to change the usual way of handling
code execution of a specific error condition when it occurs. In this way, exception handling
provides a better technique over error handling.
Just like any other object-oriented programming, PHP also uses the following keywords
related to exceptions:
Try: this means that if the exception does not trigger, the code will just execute normally but
if the exception triggers then it will call “thrown” exception
Throw: every time an exception has been triggered, a “throw” exception must be paired with
at least one “catch”
Catch: this block of code should retrieve an exception and create an object including the
exception information.
Error logs
Error logs are crucial during development because this allows developers to see the errors,
warning, notices, etc. that were logged while the application is running. Most of the time,
when a web application is deployed, all errors and warnings are suppressed to prevent
ordinary users from seeing the errors that will arise. Even though the errors and warnings are
hidden from the regular users, the web server still logs every event the website encounters.
Whenever the application is in an incorrect state in which it cannot recover, then the program
is in an error state.
Because the parameters for the mysqli_connect are incorrect, the best way to handle this kind
of scenario is the program throwing an exception. It‟s pointless that the application continue
executing because it would not still return some data from the database.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$connection2 = mysqli_connect('localhost', 'root1', 'Abc123456!', 'testx');
} catch (mysqli_sql_exception $ex) {
die("Can't connect to the database! \n" . $ex);
}
In Retrace, all errors are recorded together with some important information about that error
like the time it occurred, the method that caused it, and the exception it generated. The
number of times the error occurred in a particular time frame is also graphed. From this data,
developers can easily look at what caused the error and then apply a fix. Project managers
can also prioritize which issue to fix based on the number of occurrence of an error.
function myTestFunctionHello($str)f
{
echo "\nHi: $str";
myTestFunctionGoodbye($str);
}
function myTestFunctionGoodbye($str)
{
echo "\nGoodbye: $str";
print_r(debug_backtrace());
}
myTestFunctionHello('World');
// output
{[0]=> array(4) { ["file"]=> string(43) "\var\www\test-error.php" ["line"]=> int(6)
["function"]=> string(21) "myTestFunctionGoodbye" ["args"]=> array(1)
{ [0]=> string(5) "World" }
}
[1]=> array(4){ ["file"]=> string(43) "\var\www\test-error.php" ["line"]=> int(15)
["function"]=> string(19) "myTestFunctionHello" ["args"]=> array(1)
{ [0]=> string(5) "World" }
}}
The debug_backtrace allows developers to see which function was called first. Essentially,
this will return an array of function calls, lines, objects, class, etc. This is helpful in tracing
errors because any fix made can affect the other functions that calls or use it. A similar
function, debug_print_backtrace, also gives similar output but with more details.
echo $unknown_a;
echo $unknown_b;
print_r(error_get_last());
Array ( [type] => 8 [message] => Undefined variable: unknown_b [file] =>
C:\xampp\htdocs\monolog-test\test-error.php [line] => 4 )
The function error_get_last will get the last error in the stack trace. This can be used to
remove all the other errors displayed in the stack trace and only focus on the last error that
has occurred.
// will log to the web server error log file, will also log to Retrace
error_log("This is a sample error.", 0);
The error_log function allows developers to log errors in either the default error log of the
web server, send the error log to an email, or log the error to a specified file.
$divisor = 0;
if ($divisor == 0) {
trigger_error("Division of zero not allowed!", E_USER_ERROR);
}
This will generate a user defined error, notice, warning etc. This PHP function allows
developers to generate a specified response at runtime.
In other PHP frameworks, error handling is a lot easier and most of them are just a matter of
editing the configuration file. In Laravel, the class App\Exceptions\Handler handles all the
triggered exceptions and logging by a web application. The Handler class in Laravel has two
methods, report and render. The report method is used to send exceptions to an external
service. The report is good for logging errors without displaying it in a web page. The render
method will convert an exception into an HTTP response that needs to be sent back to the
browser.
abort(500);
abort(403, 'You are not allowed to enter!');
Throwing HTTP exceptions can easily be done in Laravel by using the abort helper. The
abort helper function has an optional response text parameter for a custom display message.
Users –The users enter wrong parameters which put a negative effect on a web application or
website.
Hackers -Hackers intentionally disrupt the application and intentionally gain access to
unauthorized data
These are the following kinds of attack:
Cross-site scripting – This kind of attack inserts a harmful code usually in JavaScript. This
can be done by using user input forms like comments forms and contact us.
SQL Injection – This Kind of attack adds harmful code to SQL statements. This can be
executed either from user input forms or URLs that use variables.
The code is being added code comments the condition in the WHERE clause of an SQL
statement.
PHP strip_tags
This strip_tags functions removes JavaScript, HTML or PHP tags from a string.
This function is useful to protect our applications from attacks such as cross site scripting.
Let’s take an example of an application that accepts comments from users.
<?php
$user_input = "phptpoint is Awesome";
echo "<h4>This is my Commenting System</h4>";
echo $user_input;
?>
Assuming you have saved comments.php "if you use XAMPP" you can do that in you
htdocs folder
Let's assume you receive the following as the user input <script>alert('welcome to
phptpoint!');</script>
<?php
$user_input = "<script>alert('welcome to phptpoint!');</script>";
echo "<h4>This is my Commenting System</h4>";
echo $user_input;
?>
Let's now secure our application from such attacks using strip_tags function.
<?php
$user_input = "<script>alert('hello phptpoint!');</script>";
echo strip_tags($user_input);
?>
If the data is of the right type then you can check the validation and you will get the false
result while checking numeric validation on a string.
<?php
$user_input = "<script>alert('Your site sucks!');</script>";
echo filter_var($user_input, FILTER_SANITIZE_STRIPPED);
?>
Let's take an example that we have the SQL statement for validating the user id and
password.
<?php
SELECT userid,pswd,role FROM users WHERE userid = 'admin' AND password = 'pass';
?>
A vicious user can enter the following code in the user login box.„OR‟ 1 = 1- And abcd in the password
text box , below is the authentication code module.
<?php
$userid = "' OR 1 = 1 -- ";
$pswd = "abcd";
$sql = "SELECT userid,pswd,role FROM users WHERE userid = '$userid' AND password = '$pswd';";
echo $sql;
?>
Output:
SELECT userid,pswd,role FROM users WHERE userid = '' OR 1 = 1 -- ' AND password = abcd;
HERE,
1. "SELECT * FROM users WHERE user_id = ''" tests for an empty user id".
2. "OR 1 = 1 " is a condition that will always be true.
3. "--" comments that part that tests for the password.
<?php
$userid = mysql_real_escape_string("' OR 1 = 1 -- ");
$pswd = mysql_real_escape_string("abcd");
$sql = "SELECT userid,pswd,role FROM users WHERE userid = '$userid' AND password = '$pswd';";
echo $sql;
?>
Output:
SELECT userid,pswd,role FROM users WHERE userid = '\' OR 1 = 1 -- ' AND password = abcd;
When storing in passwords in the database Md5 and sha1 are very useful.
<?php
echo "MD5 Hash: " . md5("password");
echo "SHA1 Hash: " . sha1("password");
?>
Assuming you have saved the file hashes.php in in your folder, browse to the URL