Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Object Oriented Programming in PHP

In this article, we will explore PHP advanced concepts like Object creation, Accessing class attributes, Data Hiding, Encapsulation, Inheritance, Polymorphism, Scope of fields & Member functions, Constructor, Destructors, etc.

In our last tutorial we have covered fundamental concepts of OOP in PHP. Those concepts include: Object creation, Accessing class attributes, Data Hiding, Encapsulation, Inheritance, Polymorphism, Scope of fields & Member functions, Constructor, Destructors, Overriding, Scope resolution operator and $this variable. Here, things gets more advanced. You will be able to learn how to handle errors, how to use base class as a template and how to work with object type hinting. Advanced OOP isn’t the scariest programming technique you’ll encounter, so by learning these concepts you’ll be able to see its beauty on higher level.

Static variables

By default, functions retain no memory of their own execution and upon calling each time the function, local variables act as they were created first time. On the other hand, declaring the variables static inside of functions will change their normal behavior and they will remember their value each time, when called. To understand it let’s move to Listing 1.

Listing 1: Creating a counter using static variable.

   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>static variables</title>
  </head>
  <body>
  <?php
  function counter(){
       static $count=0;
       echo "Count is=".$count."<br>";
       $count++;
       } 
       counter();
       counter();
       counter();
  ?>
  </body>
  </html>
   

In Listing 1 we have created a function counter( ), and inside this function a static variable $count is declared. Now upon calling this function, it will print value of $count and will increment its value by using $count++, which will be updated from 0 to 1.

Calling again the same function will print the current value present in $count and will increment the value present in it by using $count++.

So this process continues each time when you call the function as shown in Figure 1.


Figure 1. $count variable value is incremented to 2 upon calling 3 times.

PHP offers static member variables and static methods as of version 5.

Static class attributes

The concept of static class attributes is similar to that of static variables except that static class attributes are remembered by all the instances (objects) of that class. Also static class attributes can’t be accessed by using $this variable. Instead, they can be accessed by using keyword self, followed by scope resolution operator (::), followed by variable name with its initial dollar sign. For example


Listing 2: Program for using static class attributes.

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>class attributes</title>
  </head>
  <body>
  <?php 
  class counter{
       public static $count=0;
       function __construct(){
            echo "Default value is=".self::$count;
            self::$count++;
            }
  }
  $obj1=new counter();
   
  ?>
  </body>
  </html>
  

In Listing 2 we declared a Public variable $count static. And when we want to use it inside the constructor of a class or any other member function we can’t access it by $this variable. Instead we have accessed it through the following statement.

self::$count;

Upon executing, the code will display the output as shown in Figure 2.


Figure 2. Accessing static variables in class.

Static class methods

Static class methods are created the same way as that of class variables. Once you declared a function static, you can’t access it through objects of class. Instead, you will use a class name followed by scope resolution (::) and then function name. For example

Listing 3: Program for accessing static member function in class.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>static_class_methods</title>
</head>
<body>
<?php 
class counter{
     public static function count(){
          echo"This fucntion is not accessed by objects of class.";}
     }
counter::count();
 
?>
</body>
</html>
In Listing 3 a function count( ) is declared static within class counter. At the end, the member function of class is accessed by following statement as given in Listing 4

Listing 4: Accessing static function through scope resolution operator.

counter::count();
Running the code will print the message in function as shown in Figure 3.

Figure 3. Accessing static member function of class.


Class constants

Class constants are accessible to all instances of that class. As obvious from name constant, they never change their value and remain fixed. Class constants are created by using const keyword, followed by name of variable without any dollar sign, followed by assignment operator and the constant’s value.

Listing 5: Declaring constant in class.

Class classname{
 const PI=3.14; }

Like static attributes, constants can’t be accessed by objects of class. If you want to access constant you can use the following syntax.

Listing 6: Accessing constant’s in class

Class name::constant_name;
      OR
Self::constant_name;
In Listing 6 two methods are mentioned for accessing constants you can use any one.

Listing 7: Using constant in class.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>constant_in_class</title>
</head>
<body>
<?php 
class circle{
     const PI=3.14;
     function circum($rad){
          $circum=2*self::PI*$rad;
          echo"Circumference of circle is=".$circum;}}
$obj=new circle();
$obj->circum(4);
?>
</body>
</html>
In Listing 7 we declared a constant variable and then it is accessed in member function circum( ), rest of code is simple and upon running it will show output as shown in Figure 4.

Figure 4. Accessing value of constant in class.


Abstract class

An abstract class is a general class whose sole purpose is to act as a base from which other classes are derived. So classes used only for deriving purpose are called Abstract classes; meaning that no actual instances of such class are created. Classes that contain at least one abstract method must also be abstract.

Syntax

Listing 8: Abstract class and abstract function syntax

abstract class class_name{
abstract function function_name( );
}
You can also add arguments to your abstract function. But remember, you don’t need to define functionality of your method. Instead, that functionality will be determined by the class that extends the abstract class. Additionally, these methods must be defined with same visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private. Furthermore, the arguments of functions must also match. To put this into action, let’s suppose we have a math class which acts as abstract base class and we want to extend it through calc class. Let’s write a program to understand it better.

Listing 9: Implementation of abstract class.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>abstract_class</title>
</head>
<body>
<?php
abstract class math{
     abstract protected function add($num1,$num2);
     abstract protected function divide($num1,$num2);
     } 
     class calc extends math{
          public function add($num1,$num2){
                $add=$num1+$num2;
                echo"Addition of numbers=".$add,"<br>";
                }
                public function divide($num1,$num2){
                    if($num2>$num1){
                          $divide=$num2/$num1;}
                          else
                {
echo"Condition not meet:Division is not perfomed";
}
                          }
                }
     //$obj=new math(); //can't instantiat objects of abstract class
                $obj=new calc();
                $obj->add(8,4);
                $obj->divide(8,4);
?>
</body>
</html>
In Listing 9, an abstract class with name math and abstract methods add( ) & divide( ) is defined. Furthermore, the calc class is used to extend the abstract class and inside it the functionality of abstract methods are defined. At end of code we created object of child class (calc) through which arguments are passed to functions. Observing the code carefully you will see that an abstract class only acts as a template so no object of abstract class can be created and if you tried you will face an error message.

Figure 5. Abstract functions output using derived class objects.


Final

PHP 5 introduces the final keyword. Marking a method as final prevents it from being overridden by a subclass. If a class is declared as final, then it can’t be extended. So attempts to override a final method or extend a class declared as final will result in fatal error. For example

Listing 10: Program for overriding a final method and extending a final class.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php 
//final class data{
     class data{
 //final function getdata($name,$age){
       function getdata($name,$age){
         echo"Your name is ".$name,"<br>";
          echo"Your age is ".$age;}
          
                }
                class personal_data extends data{
          function getdata(){
                echo"Hi this is childclass function getdata( )<br>";}
                  function display_education($edu){
                     echo"Your eduacation is ".$edu,"<br>";}}
$obje2=new personal_data();
$obje2->getdata();
$obje2->display_education("B.E computer system");
?>
</body>
</html>
Listing 10 consists of two classes that is data and personal_data class. When you try to execute this program it will run successfully. Now let’s move to our main point, comments are present in the code so first of all changing comments of getdata( ) function in base class and leave the remaining as it is:

Listing 11: Replacing code in Listing 10 by Listing 11.

final function getdata($name,$age){
       //function getdata($name,$age){
Running this code will show error message as shown in Figure 6. Again copy code from Listing 10 and add final keyword to base class in the following way.Listing 12: Replacing code in Listing 10 by Listing 12.
        
 final class data{
     //class data{
Executing code this time will show error message as shown Figure 7.

Figure 6. Error message for overriding final method.

Figure 7. Error message shown while extending final class.


Object type hinting

Also a feature of PHP 5. Type hinting ensures that object passed to a method as an argument is the member of the expected class. Because PHP is loosely type language you can ignore type of integer and numbers. That is, they can be of any type but you can’t use objects in such a way.

Syntax

Listing 13: Syntax for type hinting

private function function_name (class_name  $obj){
//code
}
To understand this new feature of PHP, let’s write a simple program.

Listing 14: Program for accepting correct object in function arguments.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
class MyClass {
    public $var = 'Hello World';
}
function myFunction(MyClass $foo) {
    echo $foo->var;
}
$myclass = new MyClass;
myFunction($myclass);
?> 
</body>
</html>
Listing 14 consists of a class MyClass, in which a variable $var is assigned a value. Moreover, a function named myFunction( ) is defined outside of the class taking object as an argument of type class. At end of code an object of class is created and is passed to the function as an argument. The function will accept this argument as it’s of correct type and will access the variable value present inside the class through object of class.

Figure 8. Object is passed as an argument to function.


Exception Handling in PHP

Another most important feature added to PHP 5 is the ability to handle errors using try and catch statements. The method is like this that you try to do something like connectivity to a database or something else which has the potential to fail. Now if an error occurs, you will throw an exception and your code will catch the exception and will respond accordingly.

Syntax

Listing 15: Basic syntax

try
{
//do something
//throw an exception on error
}
catch(exception){
//Do whatever now
}
 
To learn exception handling in PHP, let’slook at the internals of the base exception class, how to extend this base class, define multiple catch blocks and introduce other advanced handling tasks.

PHP Base Exception Class

An exception class is a simple one and consists of a default constructor with no arguments, an overloaded constructor which takes two optional arguments, and six methods.

Default Constructor

As default constructor is no arguments constructor so it is called when an object of exception class is created.

Listing 16: Creating object of type exception.

throw new Exception( );// this code throw an object of type exception a class defined in PHP 5.
You can use this object to access all the six method of exception class. However, we use four of them, the other two are useful only when we instantiate the class with overloaded constructor.

Overloaded Constructor

An overloaded constructor offers additional functionality with the acceptance of two optional arguments.· Message: This argument consists of a user friendly message which will be passed to user through a method getMessage( ).· Error_code: This argument consists of a code which will be mapped to some identifier-to-message table.

Methods

The following six methods are available in exception class.

  • getMessage( ): the message received, if any.
  • getCode( ): the code received, if any.
  • getFile( ): the name of the file where the exception occurred.
  • getLine( ): the line number from which the exception was thrown.
  • getTrace( ):Returns an array which may consists of file name, line, function, and function arguments.
  • getTraceAsString( ): Return same information as that of getTrace( ) but in string form not array.

Note: you can’t override any of the methods described above because they are declared with the keyword final.

Listing 17: If any of the steps in this code failed, exception are thrown, to be handled by the catch.

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Exceptions</title>
</head>
<body>
<?php 
$file='info.txt';
$data="new information added";
try{
     if(!$fp=@fopen($file,'w')){
          throw new Exception("couldn't open the file");}
          if(!@fwrite($fp,$data)){
                throw new Exception("couldn't write");}
                if(!@fclose($fp)){
                     throw new Exception("couldn't close");}
                     echo"The data has been written successfully";}
                     catch(Exception $e){
          echo"the process couldn't be completed ".$e->getMessage();}
?>
</body>
</html>
Listing 17 will seem unfamiliar to you if you don’t know about file and directories in PHP. But don’t worry it’s quite simple and I will try to deliver the most and make it easy for you.PHP provides two type of functions when dealing with files, in which some uses file handles while other uses file name as a string. File handle is an integer and is used for recognition of file. We store this file handle in a variable with the help of which we can recognize a file. For example

Listing 18: Example for using file handle to open and write to file.

 $fp=fopen(“info.txt”,”w”);
fwrite($fp,’HI bool’);
In above example, we used $fp as a variable to store file handle of file. In our second line, we used fwrite( ) function to write into the file using file handle.Now coming to Listing 17, $file variable is used to store full path of file while $data variable is assigned some text which will be added to that file.After that, we started a try { block, and an attempt is made to open the file through following code in Listing 19.

Listing 19: Part of code from Listing 17.

if(!$fp=@fopen($file,'w')){
throw new Exception("couldn't open the file");}
Opening a file for writing purposes is a common task and problems may occur if the file doesn’t exists or the path given is wrong. So if the file is not opened in writing mode an exception will be thrown with the message “couldn’t open the file”. Here “@” is used as a suppression operator and will suppress any errors generated by function calls.In our next step we are going to write date to the file using code in Listing 20.

Listing 20: Part of code from Listing 17.

if(!@fwrite($fp,$data)){
throw new Exception("couldn't write");}
This step will be executed successfully if the file is opened in a previous step. This step will use fwrite( ) function to write data to file using file handle. Upon failing, exception will be thrown with the message couldn't write”.Finally, we are going to close the file with a display message using the code in Listing 21.

Listing 21: Part of code from Listing 17.

if(!@fclose($fp)){
throw new Exception("couldn't close");}
echo"The data has been written successfully";}
At end of Listing 17, we have used the following code for catching and handling, the exception.

Listing 22: Part of code from Listing 17.

catch(Exception $e){
echo"the process couldn't be completed ".$e->getMessage();}
$e is an object of type Exception, matching the type of exception thrown. In this block getMessage( ) is used to print the received message.

Figure 9. Using exception, success message is shown.

Figure 10. Assigning wrong address of file will show this message using exceptions.


Extending the Exception class

You can extend the base class (exception) for adding or changing extra functionality according to your need. Extending the Exception class is similar to extending any other class. Also, you can override the Exception constructor only as rest of the methods are declared final.

Syntax

Listing 23: Syntax for extending Exception class

class MyException extends Exception{
// codes goes here
}
try {
//some code
throw new MyException (‘error message’);
}
catch(MyException $e)
{}
 

Listing 24: Extending Exception class to create a more specific type of exception handling.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Extending_exception_class</title>
</head>
<body>
<?php 
class FileException extends Exception{
     function get_details(){
          switch($this->code){
                case 0:
                return 'No filename was provided';
                break;
                case 1:
                return 'The file does not exist';
                break;
                case 2:
                return 'The file is not a file';
                break;
                case 3:
                return 'The file is writable';
                break;
                case 4:
                return 'An invalid mode was provided';
                break;
                case 5:
                return 'The data could not be written';
                break;
                case 6:
                return 'The file could not be closed';
                break;
                default:
                return 'No further information is available';
                break;}
                
     }
}
          
          class WriteToFile{
                private $fp= null;
                private $message='';
                function __construct($file=null,$mode='w'){
                     $this->message="File:$file Mode:$mode";
                     if(empty($file)){
                          throw new FileException($this->message,0);}
                          if (!file_exists($file)) {
                     throw new FileException ($this->message, 1);
                     if (!is_file($file)) {
                throw new FileException ($this->message, 2);}
                if (!is_writable($file) ) {
                     throw new FileException ($this->message, 3);}
                if (!in_array($mode, array('a', 'a+', 'w', 'w+'))) {
                throw new FileException($this->message, 4);}
                $this->fp = fopen($file, $mode);}
                function write($data = null) {
 
 if (!fwrite($this->fp, $data)) {
 throw new FileException($this->message . " Data: $data", 5);
 }}
 function close() {
 if (!fclose($this->fp)) {
 throw new FileException($this->message, 6);
 }
 
 $this->fp = null;}}
 $file = 'data.txt';
 $data = "This is a line of data.\n";
 try {
 $fp = new WriteToFile($file);
 $fp->write($data);
 $fp->close();
 echo '<p>The data has been written.</p>';
 } catch (FileException $fe) {
 echo '<p>The process could not be completed. Debugging information:<br />' . 
$fe->getMessage() . '<br />' . $fe->get_details() . '</p>';
 }
?>
</body>
</html>
In Listing 24, two classes are present one is FileException, which extends Exception class while the other is WriteToFile . The class FileException will be used to handle file opening, writing, and closing errors. Moreover, it will add one method to the inherited Exception class. Any time an exception occurs, up to two arguments can be passed to Exception class: the message and the error code. The WriteToFile, will generate its own error codes. The class, FileException, will map those error codes with more specific error messages. And this job is done by get_details( ) method which will return those messages that goes with each code using a switch. In class WriteToFile, two private attributes are defined, one is used for file pointer while the other is used for error message. A constructor is created which takes two arguments: the file and the mode, whose default value is w. Constructor is used to assure that the file exists and is writable.To check that a file name was provided we check it through empty( ) function. The following code is used for this purpose.

Listing 25: Part of code from Listing 24.

if(empty($file)){                                                   
throw new FileException($this->message,0);
}    
If the file name was not passed to this function, an exception will be thrown, using default message and error code. After passing a file name, to make it sure that it’s a file name and it exists the following code is used.

Listing 26: Part of code from Listing 24.

if (!file_exists($file)) {
   throw new FileException ($this->message, 1);
}
if (!is_file($file)) {
   throw new FileException ($this->message, 2);
}                 
If each of the above functions failed an exception will be thrown with related error code. To confirm that the file is writable and no restriction are present this section of code is used

Listing 27: Part of code from Listing 24.

if(!is_writable($file) ) {
   throw new FileException ($this->message, 3);
}
To confirm that a valid mode was used

Listing 28: Part of code from Listing 24.

if (!in_array($mode, array('a', 'a+', 'w', 'w+'))) {
	throw new FileException($this->message, 4);
}
Here a, a+, w, and w+ are modes for fopen( ).a = Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.a+=Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.w=Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.w+=Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.After this, the file is opened and assigned to $fp

Listing 29: Code for opening file.

$this->fp = fopen($file, $mode);}
Two more methods are created: one for writing data to file and other for closing the file. At end of code, two attributes are used. One for identification of file and the other for writing data to file. Also a try and catch block is used. The catch expects exception of type FileException, which will be thrown by the WriteToFile object. Using catch, debugging information is printed using both the Exception getMessage( ) and FileException get_details( ) methods.

Figure 11. Error message shown when “data.txt” is not created and you try to run the program.

Figure 12. Message shown when data is written to file.


Conclusion

The topics covered in this tutorial touch upon the static concept used in a class, how to use abstract classes, how to identify object of a specific class , and many of the core error-handling practices used in today’s programming industry. The ability of error handling has helped programmers detect and respond to otherwise unforeseen problems in their code. Based to this, you are now able to communicate in an OOP way. All of the main topics in OOP are covered. If you want to learn more and get hands-on examples, refer to OOP manual which is one of the best tutorial for PHP where you will be able to study comments, examples, and suggestion in the user contributed notes section.



Software developer doing B.E in Computer Science at Hamdard university karachi. Have good skills in php, html, javascript and css.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login