Author - StudySection Post Views - 42 views
OOP In PHP

Fast Paced Introduction to OOP in PHP

What is Object Oriented Programming?

Object oriented programming is a programming language, which is linked to the concept of classes and objects and many concepts revolving around them, such as inheritance, polymorphism, abstraction, encapsulation, etc.

php-oop

Class in PHP (OOP)

Let’s take Human Being as a class. A class is a blueprint/template for objects which defines its properties and its functions. For e.g. Human Being has body parts and performs various actions.

PHP is an object oriented programming language, allows us to create classes and objects to follow the object oriented programming paradigm while developing any application.

A class is a user-defined data type that includes local variables and local methods. While an object is an instance of the class which holds the local variables with values assigned and on which we can call the local methods defined in the class.

The syntax for defining a Class in PHP
The syntax for defining a class in PHP is very simple. We use the keyword class followed by the name of the class and then we enclose the code for the class within curly braces { } just like for a method.

Functions, when defined inside a class are called methods. Inside a class, methods are defined to either perform some operation on the class variables(properties) or perform some other operation for the class. A class generally includes local variables and local methods.

An object is an instance of the class which holds the local variables with values assigned and using the object we can call the local methods defined in the class.

eg:
<?php
class Example1{
var $url = "google.com";
// simple class method
function desc() {
echo "Google search engine";
}
}
// creating class object
$obj = new Example1();
?>

To access class variables and methods using the object of the class, we use the -> operator followed by the name of the variable or the method’s name.

oop-method

Inheritance

Considering Human Being a class, having properties like hands, legs, eyes, etc, and functions like walk, write, talk, see, etc. male, female are also classes and most of the properties are included in Human being class, so they can inherit everything from it using the concept of Inheritance. Inheritance enables classes to form a hierarchy like a family tree and allows reusing code.
Syntax:

<?php
class Human {
// parent class code
}
class male extends Human {
// child class code
}
class female extends Human {
// child class code
}
?>

Objects

My name is Anshul and I am an instance/object of class Male. When we say, Human Being, Male or Female, we mean a kind, you, your companion, me we are the forms of these classes. We have a physical presence, whereas a class is just a logical definition. We are the objects. The fundamental idea behind an object-oriented language is to enclose a bundle of variables and functions into a single unit and keep both variables and functions safe from outside interference and misuse.

Such a unit is called an object which acts on data. The functions of an object are called methods and all the methods of an object have access to variables called properties.

Instantiate/creating the object
Classes do not become objects until you are doing something called: instantiation. After you instantiate a class, you create an instance of it, hence creating the object. In other words, instantiation is the process of creating an instance of an object in memory.

<?php include("class_lib.php"); ?>
</head>
<body>
<?php
$abc = new person();
?>
</body>
</html>

Note: The variable $abc becomes a handle/reference to our person class. I call $abc a ‘handle’, because we will use $abc to control and use the person class methods. In case you run the PHP code now, you may not see anything shown on your pages. The reason for this is that we have not told PHP to do anything with the object we just created.

The ‘new’ keyword
For creating an object out of a class, you must use the ‘new’ keyword. When creating/instantiating a class, you can optionally add brackets to the class name, as I did in the example below.
From the PHP point of view, each object is its’ own entity.

<?php include("class_lib.php"); ?>
</head>
<body>
<?php
$abc = new person();
$jim = new person();
?>
</body>
</html>

Note: While creating an object, don’t quote the class name. For example:
$abc = new ‘person’; will get you an error.

Abstraction

Abstraction means, displaying only the specified things to the exterior world whereas hiding the details. Proceeding our illustration, Human beings can talk, walk, listen, eat, but the details are hidden from the exterior world. We can take our skin as the Abstraction factor in our case, hiding the interior mechanism.
Example:

<?php
abstract class Animal
{
public $name;
public $age;
public function Describe()
{
return $this->name . ", " . $this->age . " years old";
}
abstract public function Greet();
}
class cat extends Animal
{
public function Greet()
{
return "Lion";
}
public function Describe()
{
return parent::Describe() . ", and I'm King";
}
}
$animal = new cat();
$animal->name = "Haider";
$animal->age = 4;
echo $animal->Describe();
echo $animal->Greet();
?>

Encapsulation

This concept may be a bit tough to clarify with our illustration. Our Legs are binded to help us walk. Our hands, facilitate us hold things. This binding of the properties to functions is named Encapsulation.

Example:

<?php
class App {
private static $_user;
public function User( ) {
if( $this->_user == null ) {
$this->_user = new User();
}
return $this->_user;
}
}
class User {
private $_name;
public function __construct() {
$this->_name = "john";
}
public function GetName() {
return $this->_name;
}
}
$app = new App();
echo $app->User()->GetName();
?>

With Encapsulation, you can control, access and set class parameters and methods. You have control and set, which portion is visible to outsiders and how one can you set your objects parameters?

Polymorphism

Poly means many and morph means forms. Polymorphism is a concept, which permits us to redefine the way something works, by either changing how it is done or by changing the parts using which it is done. Both ways have distinctive terms for them.

Polymorphism describes a pattern in Object Oriented Programming in which a class has different functionality whereas sharing a common interface.

Example:

<?php
class Shape
{
function draw(){}
}
class Circle extends Shape
{
function draw()
{
print "Circle has been drawn.
";
}
}
class Triangle extends Shape
{
function draw()
{
print "Triangle has been drawn.
";
}
}
$Val=array(1);
$Val[0]=new Circle();
$Val[1]=new Triangle();
for($i=0;$i<2;$i++) { $Val[$i]->draw();
}
?>

Output:
Circle has been drawn
Triangle has been drawn

PHP 5 Access Modifiers

We use access modifiers to set access rights for class methods and variables that are nothing but PHP keywords. We can even assign some of these access modifiers to the class itself to make the class behave in a special way.

The following are PHP keywords used as access modifiers along with their meaning:

  • Public: When we define class members as public, they are accessible from anywhere, even outside the scope of the class.
  • Private: When we define class members as private, they can only be accessed from within a class.
  • Protected: This is similar to private, with one exception, a class member defined as protected is still accessible from its subclass.
  • Abstract: This keyword is used only for PHP classes and its member functions.
  • final: The class methods defined as final, can not be changed or overridden by any subclass.

Getter and setter functions
I’ve created two interesting functions/methods: get_name() and set_name(). These methods follow a common OOP convention that you see in many languages where you create methods to ‘set’ and ‘get’ properties in a class.

Another convention (a naming convention), is that getter and setter names must match property names.

<?php
class person {
var $name;
function set_name($new_name) {
$this->name = $new_name;
}
function get_name() {
return $this->name;
}
}

Note that the names of the getter and the setter match the name of the associated property.

That way, when other programmers want to use your objects, they will know that if you have a function called ‘set_name ()’, then there will be a property/variable called ‘name’.

The ‘$this’ variable
You noticed this line of code: $ this-> name = $ new_name. $ This is a built-in variable (built into all objects) that points to the current object. Or in other words, $this is a special self-referencing variable. You use $this to access properties and to call other methods of the current class.

function get_name() {
return $this->name;
}

For now, just think of $this as a special PHP keyword. The PHP engine knows what to do when it comes across $this.

Note: Include class in the main PHP page
You’ll never create your PHP Php class directly inside your main PHP pages – which will help defeat the objectives of object-oriented PHP in the first place.

Instead, it is always best practice to create separate PHP pages that contain only your classes. You will then access your PHP objects/classes by including them in your main PHP pages by either a PHP ‘include’ or ‘require’.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>OOP in PHP
<?php include("class_lib.php"); ?>
</head>
<body>
</body>
</html>

Note: Notice how we haven’t done anything with our class yet.

PHP OOP Interfaces

When you need to let a class to compulsorily implement some methods in it, you can use interfaces. This is a good practice when creating real-world web applications in PHP.
If you need to support child classes by adding some non-abstract methods, then you should use abstract classes.

interface

Example:

<?php
Interface Person {
public function __construct($name);
public function greet() : string;
}

class Programmer implements Person {
public $name;
public function __construct($name) {
$this -> name = $name;
}
public function greet() : string {
return "Hello world from " . $this -> name;
}
}
$programmer = new Programmer('john');
echo $programmer -> greet();

Output: Hello world from john

An interface can only have method signatures. It means that all the methods cannot have a body – only the declaration.
After implementing an interface in a class, all the abstract methods in the interface should be declared in the class.
As all the abstract methods in an interface have public visibility, all the methods in the class that implements the abstract methods should have public visibility.

PHP OOP Static

Static methods can be called directly without the need for an instance of the class (an object). And, $this pseudo-variable is not available inside static methods.
Static methods can be accessed from outside the class using the class name and Scope Resolution Operator (::). (Only if the visibility is public)
Static methods can be accessed from the methods in the same class using the self keyword and::
Example:

<?php
class MyClass {
public static function callme() {
echo "hey!";
}
public function __construct() {
self::callme();
}
}
MyClass::callme();
echo "
";
new MyClass();

Output:
hey!
hey!

The English language is the most widely used language as a medium of communication around the world. Having a certification for the English language can be an advantage. StudySection provides an English certification exam that tests English language proficiency in English grammar, reading, and writing.

Leave a Reply

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