in ,

Object-Oriented PHP & PHP Coding Tutorial for Beginners

 Understanding Object-Oriented Programming

Object-Oriented programming is considered as a coding style which enables the web-developers to congregate identical tasks into classes. However, it lets you to buoy up the code through “don’t repeat yourself” (DRY) principle and is very affable to cultivate.

One most significant and worthy feature of DRY programming is that when a fragment of information alters in your program, generally one change is supposed to upgrade the code. However, one of the major illusion for developers is cultivating the code while data is supposed to be declared most often, which stands for any modification being implemented to the program become more frustrating as they investigate for duplicate data and functionality.

As, OOP is introduces various new syntax and at a glance supposed to be more confounded in contrast of simple procedural or inline code, thus threatens to most of the developers.

Comprehending Objects and Classes

Prior to indulge in nitty gritty insight of the OOP’s finer points, it is necessary to comprehend the fundamental differences between objects and classes. However, this section will take you through building blocks of classes, concerned distinct abilities as well as their uses.

Recognizing the Differences Between Objects and Classes

Lets know the difference between objects and classes with reference to this illustration. A class is something identical to a blueprint for a house. It determine the shape and planning of the house on paper through establishing a link amongst distinct sections of the house defined and planned clearly, even though no existence of the house.

An object is like the actual house built in accordance of that blueprint. However, the stored data in object is like wires, wood and concrete which construct the house. Furthermore, it’s just a aggregation of stuff, if not assembled properly according to the blue print. Thus, when amassed together, results in a useful and organized house.

Classes form data structure and action as well as employ information for Objects building.

In the mean time by identical class, independent multiple object can be created where no object will interfere others. However, following our analogy of construction. It seems to similar to the procedural to built an entire subdivision in accordance of the same blueprint. Where, 150 distinct houses convey same structure and look but comprises distinct families and inside decorations.

Structuring Classes

The syntax of creating a class is very simple and easy; just declare a class in account of class keyword, followed by class name and curly braces {}sets.

<?php

class MyClass
{
// Class properties and methods go here
}

?>

After accomplishing this, you can assign a new class and save in a variable through employing a new keyword:

$obj = new MyClass;

Now, in order to view the contents of the class, you can employ var_damp():

var_dump($obj);

Test this process by incorporating these code snippet in a new file called test.php at your local folder.

<?php
class MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj);
?>

Now, you are required to upload this page to your browser at http://localhost/test.php and eventually something will appear should be like this:

object(MyClass)#1 (0) { }

With this, you have successfully accomplished your first Object-Oriented PHP script.

Defining Class Properties

Class-specific variables or class, properties are used to add data. However, likewise other regular variable it also works except those who are bound to the object and hence can be accessed only by employing the object. In order to add a property to MyClass, you are required to put the following snippet code to your script:

<?php
class MyClass
{
public $prop1 = "I'm a class property!";
}
$obj = new MyClass;
var_dump($obj);
?>

Where, the keyword public defines the property visibility, about which you will know later in coming next section. Next, through standard variable syntax a name to the property is assigned as well as a value too. (though class properties don’t require initial value).

In context to read this property and final output to browser, you are supposed to reference the object by property you wish to read.

echo $obj->prop1;

Where the arrow (→) is known as an OOP construct which used to access the method and contained properties assigned to a given object. Moreover, it is possible that multiple instances of a class may exist. So, when an individual object wouldn’t be referenced then the script can’t determine the object to read from.

Therefore, you are required to alter the script in test.php test file in order to read property instead of dumping the entire class through changing the code as listed below.

<?php
class MyClass
{
public $prop1 = "I'm a class property!";
}
$obj = new MyClass;
echo $obj->prop1; // Output the property
?>

After reloading your browser you will get following outputs:

I’m a class property!

Defining Class Methods

One most significant amongst class-specific functions is Methods. An object which is capable to perform an individual actions is falls under the class as methods. As for example, in order to create methods which can be set and fetch value of the class property $prop1, include below provided snippet to your code:

<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}
$obj = new MyClass;
echo $obj->prop1;
?>

Here is a noticeable point that by using $this OOP winks object to referenced themselves. While you are supposed to work within a method, you should employ $this likewise same way as you would employ the name of object outside the class.

However, in context of applying these methods, likewise other common regular function call them also, but first of all you are required to reference the concerned object. Now, modify the value after reading the property from MyClass and then read it again after implementing the alteration below:

<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}
$obj = new MyClass;
echo $obj->getProperty(); // Get the property value
$obj->setProperty("I'm a new property value!"); // Set a new one
echo $obj->getProperty(); // Read it out again to show the change
?>

After reloading the browser you will get the following:

I’m a class property!
I’m a new property value!

In the case of applying multiple instances of the same class the power of OOP renders to more apparent.

<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}

// Create two objects
$obj = new MyClass;
$obj2 = new MyClass;

// Get the value of $prop1 from both objects
echo $obj->getProperty();
echo $obj2->getProperty();

// Set new values for both objects
$obj->setProperty("I'm a new property value!");
$obj2->setProperty("I belong to the second instance!");

// Output both objects' $prop1 value
echo $obj->getProperty();
echo $obj2->getProperty();

?>

When you will load this result to your browser, it will read as says below:

I’m a class property!
I’m a class property!
I’m a new property value!
I belong to the second instance!

However, you can see here that OOP conveys asunder entities to objects, which tends them to separate easily from distinct snippet of code into small and respective bundles.

Magic Methods in OOP

Towards the endeavor of easier employment, PHP also offer various magic methods or called as special methods which are useful to employ in the case when some specific common actions hit within the objects. Thus, it enables the web-developers to pursue quantity of worthy actions with relative comfort.

Employing Constructors and Destructors

PHP offers a magic method called _construct() which is very helpful when a new object come into existence it called it automatically. Towards clarifying the concept of constructors, include a constructor to MyClass which results in output a message when it designate that a new class has been created:

<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}

// Create a new object
$obj = new MyClass;

// Get the value of $prop1
echo $obj->getProperty();

// Output a message at the end of the file
echo "End of file.<br />";

?>

Note: __CLASS_ says the class name where it is called, however, this is the things known as a magic constant. There are lot of magic constants available that can be read out in the PHP manual.

Following result will appear after reloading the file to your browser:

The class “MyClass” was initiated!
I’m a class property!
End of file.

When an object is destroyed call this function, the _destruct() magic method. It is quite obvious for class cleanup.

It delivers a message when an object is supposed to be destroyed through determining the magic method _destruct() in MyClass:

<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}

public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}

public function setProperty($newval)
{
$this->prop1 = $newval;
}

public function getProperty()
{
return $this->prop1 . "<br />";
}
}

// Create a new object
$obj = new MyClass;

// Get the value of $prop1
echo $obj->getProperty();

// Output a message at the end of the file
echo "End of file.<br />";

?>

After determining a destructor, you will got this below assigned result after reloading the test file:

The class “MyClass” was initiated!
I’m a class property!
End of file.
The class “MyClass” was destroyed.

PHP automatically used to unleashed all resources when the end of a file is arrived.

In context to trigger the destructor apparently, by implementing the unset() function you can destroy the object.

<?php

class MyClass
{
public $prop1 = "I'm a class property!";

public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}

public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}

public function setProperty($newval)
{
$this->prop1 = $newval;
}

public function getProperty()
{
return $this->prop1 . "<br />";
}
}

// Create a new object
$obj = new MyClass;

// Get the value of $prop1
echo $obj->getProperty();

// Destroy the object
unset($obj);

// Output a message at the end of the file
echo "End of file.<br />";

?>

After loading to the browser the result changes and appears something like this:

The class “MyClass” was initiated!
I’m a class property!
The class “MyClass” was destroyed.
End of file.

Converting to a String

To check any error when a script try to deliver MyClass as a string, _toString() is an another magic method is implemented.
Attempting to deliver the object as a string without _toString() results in a fatal error. Implement echoto which output the object apart from a magic method.

<?php

class MyClass
{
public $prop1 = "I'm a class property!";

public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}

public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}

public function setProperty($newval)
{
$this->prop1 = $newval;
}

public function getProperty()
{
return $this->prop1 . "<br />";
}
}

// Create a new object
$obj = new MyClass;

// Output the object as a string
echo $obj;

// Destroy the object
unset($obj);

// Output a message at the end of the file
echo "End of file.<br />";

?>

It shows the following output:

The class “MyClass” was initiated!

Catchable fatal error: Object of class MyClass could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/testing/test.php on line 40

In order to eliminate this error, you can add a _toString() method:

<?php

class MyClass
{
public $prop1 = "I'm a class property!";

public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}

public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}

public function __toString()
{
echo "Using the toString method: ";
return $this->getProperty();
}

public function setProperty($newval)
{
$this->prop1 = $newval;
}

public function getProperty()
{
return $this->prop1 . "<br />";
}
}

// Create a new object
$obj = new MyClass;

// Output the object as a string
echo $obj;

// Destroy the object
unset($obj);

// Output a message at the end of the file
echo "End of file.<br />";

?>

While attempting to render the object to a string output in a call to getProperty() method. You can upload the test script to your browser in context of viewing the result:

The class “MyClass” was initiated!
Using the toString method: I’m a class property!
The class “MyClass” was destroyed.
End of file.

Using Class Inheritance

In account of extends keyword classes can easily inherit the properties and methods of another class. For example, in order to create a second class which enhances the MyClass and include a method, you are required to put the following snippet in your test file:

<?php

class MyClass
{
public $prop1 = "I'm a class property!";

public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}

public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}

public function __toString()
{
echo "Using the toString method: ";
return $this->getProperty();
}

public function setProperty($newval)
{
$this->prop1 = $newval;
}

public function getProperty()
{
return $this->prop1 . "<br />";
}
}

class MyOtherClass extends MyClass
{
public function newMethod()
{
echo "From a new method in " . __CLASS__ . ".<br />";
}
}

// Create a new object
$newobj = new MyOtherClass;

// Output the object as a string
echo $newobj->newMethod();

// Use a method from the parent class
echo $newobj->getProperty();

?>

Following will be the output, when you will upload it to your browser:

The class “MyClass” was initiated!
From a new method in MyOtherClass.
I’m a class property!
The class “MyClass” was destroyed.

Overwriting Inherited Properties and Methods

You can modify the functionality of an existing method or property simply by overwriting and declare it again in the new class:

<?php

class MyClass
{
public $prop1 = "I'm a class property!";

public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}

public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}

public function __toString()
{
echo "Using the toString method: ";
return $this->getProperty();
}

public function setProperty($newval)
{
$this->prop1 = $newval;
}

public function getProperty()
{
return $this->prop1 . "<br />";
}
}

class MyOtherClass extends MyClass
{
public function __construct()
{
echo "A new constructor in " . __CLASS__ . ".<br />";
}

public function newMethod()
{
echo "From a new method in " . __CLASS__ . ".<br />";
}
}

// Create a new object
$newobj = new MyOtherClass;

// Output the object as a string
echo $newobj->newMethod();

// Use a method from the parent class
echo $newobj->getProperty();

?>

It display the output which sits below in your browser:

A new constructor in MyOtherClass.
From a new method in MyOtherClass.
I’m a class property!
The class “MyClass” was destroyed.

Preserving Original Method Functionality While Overwriting Methods
If you want to include some new functionality to an inherited method even buoying up the implemented original method, you can employ parenkeyword with scope resolution operator (::):

<?php

class MyClass
{
public $prop1 = "I'm a class property!";

public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}

public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}

public function __toString()
{
echo "Using the toString method: ";
return $this->getProperty();
}

public function setProperty($newval)
{
$this->prop1 = $newval;
}

public function getProperty()
{
return $this->prop1 . "<br />";
}
}

class MyOtherClass extends MyClass
{
public function __construct()
{
parent::__construct(); // Call the parent class's constructor
echo "A new constructor in " . __CLASS__ . ".<br />";
}

public function newMethod()
{
echo "From a new method in " . __CLASS__ . ".<br />";
}
}

// Create a new object
$newobj = new MyOtherClass;

// Output the object as a string
echo $newobj->newMethod();

// Use a method from the parent class
echo $newobj->getProperty();

?>

It displays result of both the new class’s constructor and parent constructor:

The class “MyClass” was initiated!
A new constructor in MyOtherClass.
From a new method in MyOtherClass.
I’m a class property!
The class “MyClass” was destroyed.

However, perhaps it will be proved as quite obvious and significant for you. Object-Oriented PHP will literally be easy to read and maintain, portable code that will save you precious time and additional efforts of repeating functions most often.

What do you think?

Written by Admin

Nola J Arney is working as an application and web developer at HTMLPanda. Her core technical skill in web designing, Sencha touch, PhoneGap, and other platforms has contributed a lot of benefits to the business. She has an interest in writing and hence, she has written numerous blogs & articles that specifically shed a light on website the designing & development technology. All her write-ups have earned a gratitude from the specialists worldwide.

Comments

Leave a Reply

Leave a Reply

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

Loading…

0

Comments

0 comments

Social Icon Set: A Must have Collection of Free Social Icon Set

A Must have Free Tools For Creating Charts, Flowcharts and Diagrams