VivekMishra

Inheritance In Php

Posted on: March 9, 2008

The include() Function


PHP gives you the ability to “hide” code. This is particularly helpful when creating large web environments with numerous pages that require a lot of maintenance. Think of hiding in terms of an HTML template — with an HTML template, you can guarantee uniformity across large numbers of pages as well as save coding time and effort by eliminating redundancy. By hiding code with PHP, you can feed the equivalent of a template to any given page simply by using the include() function.

For instance, if you have a standard heading for all pages on a site you can create a document named header.inc like the following:

<?php
 
   echo '<html>';
   echo '<title>Bob's</title>';
   echo '<body>';
   echo 'Bob's Towing Yard <img src="bobs_logo.jpg">';
 
?>

header.inc sets the title of the page to “Bob’s” and begins the body content of the page with “Bob’s Towing Yard” and Bob’s logo (bobs_logo.jpg). You then include this code by calling the function include() in the appropriate section of your PHP page. We’ll call the page index.php:

<?php
 
   include(header.inc);
 
?>

After you call the include() function you can add any unique content you desire. Viola, you have header uniformity across any page that includes header.inc. Of course, it isn’t a stretch to see that this can also be applied to uniform sections such as the footer of a web page, navigation menus, side panels, etc.

This immediately makes each page a 6-10 line project instead of a 20-40 line project. Once you have the included elements all dialed in, the only part of a web page you have to update is the content that is unique to the situation. In addition, if you need to change something miniscule, like Bob’s logo, or even the name Bob, the only place you have to make the change is in header.inc. All of the pages using header.inc will be automatically updated.

Note: It bears mentioning that the extension .inc is primarily used to differentiate include files from .php files. When looking at a directory of files it can be a bit daunting to pick out which files are merely include files and which are valid PHP pages. There is a difference in how browsers read these files however, and that difference should be kept in mind when creating a webpage. .inc files are treated as plain text and are therefore sent through the browser as plain text. If you view source on a page using .inc files, you will see the contents of these files. If the information contained in the .inc file is sensitive (i.e. passwords, personal information) it is best to use the .php extension so that the information is not readily available. You can also save .inc files outside of the directory, but I have always preferred to keep information that I want to be invisible under the .php extension. Files using the .php extension are treated exactly the same when called by the include() function:

include(header.inc)

and

include('header.php')

will give you the same results.

If you are using an Apache server, you can also manipulate the server configuration so that a user may not access .inc files.

Classes in Session


Now we know that we can feed whatever redundant elements we like into any number of pages by simply invoking a single function, let’s take it a step further and introduce classes.

Classes start using the Object-Oriented Programming (OOP) methodology in PHP (OOP is only available in PHP versions 4.0 and later). Briefly, OOP uses objects, which are unique and identifiable collections of stored data and operations that operate on that data. These objects are not unlike real-life objects, such as a chair, or a table. An object can also be a navigation menu, a button, a text field or a style sheet. Objects can further be grouped into classes. Classes are collections of objects that share certain criteria but may vary from object to object. For example, using horses as a class, certain criteria are necessary for an object to be classified as a horse: four legs, hooves, mane. However, many aspects of these criteria can have different values: black mane, brown mane, white mane, and so on.

This is the basic structure of a class:

class classname
{
}

To create a class in PHP, we begin with the keyword class, and the classname will follow. Next we will create attributes and operations for our class and place them between the brackets. Attributes are declared as follows:

class classname
{
   var $attribute1;
   var $attribute2;
}

Operations are created by declaring functions within the class definition:

class classname
{
   function operation1()
   function operation2($param1, $param2)
}

The function operation1 takes no parameters, while operation2 takes two parameters (param1, param2).

Most classes will have a special operation called a constructor. A constructor is called as soon as an object is created and serves the purpose of setting reasonable values for attributes or creating other objects needed by the parent object. A constructor is called in the same way a class is called, but it shares the name of the class. A constructor can be called manually, but its main purpose is to be called automatically when an object is created. This is the structure of a class that uses a constructor:


class classname
{
   function classname($param)
   {
      echo "The Constructor will be called with the
            parameter $param";
   }
}

Now that we have declared a class, we need to create an object that belongs to that class. This is also called instantiation, creating an instance of the class. So we’ll declare a class, give it a constructor, and then create two objects. The object is created using the keyword new:

class classname
{
   function classname($param)
   {
      echo "The Constructor will be called with the
      parameter $param";
   }
}
 
$x = new classname('Ego');
$y = new classname('Sum');

Our constructor is called by both objects, so the output will look like this:

The Constructor will be called with the parameter Ego
The Constructor will be called with the parameter Sum

 

 


Attributes and Operations


Earlier, when we discussed the nature of objects we compared them to horses. In order to qualify as a “horse” an object must meet certain criteria such as four legs, hooves, mane. These are our object’s attributes. Without these atributes nothing will differentiate a “horse” from a “lizard”. Thank you Captain Obvious, no one will ever mistake a horse for a lizard! That is true, but it’s very easy to mix up a “home” button that takes a user to index.php and a “home” button that takes them to my_personal_index.php. While both buttons may look identical to the user, their individual purposes are quite different, and thus their individual attributes make all the difference in the world.

Variables allow us to keep elements our of code dynamic by replacing static values with values that change according to user intervention. Attributes are no different, and as such can be written to change fluidly as the user interacts with the page.

Within a class, you have access to a special variable called $this. If you have an attribute called $decide, you refer to it as $this->decide when you are setting the attribute from an operation within the class. For example:

class classname
{
   var $decide;
   function form($param)
   {
      $this->decide = $param;
      echo $this->decide;
   }
}

This class declares a variable $decide, then uses the operation form (which is passed the parameter $param) to set the parameter to $decide. Written in code-speak, the class looks like so: $this->decide = $param. Fianlly, it accesses the attribute by printing it: echo $this->decide.

Operations are called in the same way attributes are called. First we declare our class:

class classname
{
   function form1()
   {
   }
   function form2($param1, $param2)
   {
   }
}

Then create an object:

$z = new classname();

Finally, we call the operations in the same way we call other functions, by name. However, because these operations belong to an object rather than a normal function, we must identify the object to which they pertain. We use the object’s name in the same way as the object’s attributes:

$z->form1();
$z->form2(2, 3);

If our operations return values we can retrieve them as variables like so:

$a = $z->form1();
$b = $z->form2(2, 3);

Still with me? All of this is pretty simple, mostly thanks to PHP’s logical nature. Pretty soon, we’ll see how complete classes can be used to load major elements of a page. First, let’s see how classes inherit attributes and operations from the classes above them.


Page 5 — Inheritance


Inheritance is what makes using classes more robust than simply using an include file. With inheritance, we can create a hierarchal relationship between classes and subclasses. A subclass inherits attributes and operations from its superclass, (the class above it in the hierarchy). Once again, we can save time and effort by writing a base superclass instead of spreading redundant operations over several classes. This base can then be inherited by subclasses and refined to meet even more specialized criteria.

To implement inheritance in PHP we use the keyword extends. For instance, the statement “class B extends class A” creates a Class B that inherits from Class A.

So if we have these classes:

class A
{
   var $decide1;
   function form1()
   {
   }
}
 
class B extends A
{
   var $decide2;
   function form2()
   {
   }
}

The following are valid accesses of operations and attributes from an object of type “B”:

$b = new B();
$b->form1();
$b->form2();
$b->decide1 = x;
$b->decide2 = y;

In addition, the following are valid for an object of the type “A”:

$a = new A();
$a->form1();
$a->decide1 = x;

However, inheritance only works one-way, so the following:

$a->form2();
$a->decide2 = y;

are not valid because form2() and $decide2 were created in class B. Class A does not inherit from Class B. This inheritance dynamic is also used to override values. For instance, if we declare a class A and class B again:


class A
{
   var $y = 'the first value';
   function form1()
   {
      echo "Our variable is $this->y";
   }
}
 
class B extends A
{
   var $y = 'the new value';
   function form1()
   {
      echo "Our variable is $this->y";
   }
}

class A is unaffected by declaring class B. The following is still the output of declaring Class A and creating an object of type A:

$a = new A();
$a->form1();

The above declaration will return:

Our variable is the first value

If we create an object of type B, like this:

$b = new B();
$b->form1();

it will return:

Our variable is the new value

 

 


Classes Put Into Action


Now, with your knowledge of classes and of the include() function, you can start setting up pages which contain objects that reference classes contained in included files. It all sounds a little complicated, but trust me. You’ll thank me shortly.

Let’s begin by creating a simple navigation menu to display on all of our site’s pages. We’ll name this document mainmenu.inc:

<?php
 
class mainmenu
{
                function mainmenu()
                {
                   echo '<table align="center" width="360" cellpadding="0"
  cellspacing="5">';
                   echo '<td><h2><center><a 
href="home.php">HOME</a></h2></td>';
                   echo '<td><h2><center><a
  href="services.php">SERVICES</a></h2></td>';
                   echo '<td><h2><center><a
  href="portfolio.php">PORTFOLIO</a></h2></td>';
                   echo '<td><h2><center><a
  href="contact.php">CONTACT</a></h2></td>';
                   echo '</table>';
                }
}
?>

We have created a class named mainmenu, we have also created a constructor named mainmenu so that when an object of the mainmenu type is created, it will perform the code within the class. The code within the function mainmenu is a pretty straightforward horizontal menu. There are different methods for producing this effect, such as storing the button names and URLs as a variable array, but we’ll keep it simple for the sake of introduction and let you go wild on it when you put it into practice.

Let’s create one more class before we create the page, shall we? Let’s tackle a stylesheet. We’ll call this styles.inc:


<?php
 
class stylesMainMenu
{
                function stylesMainMenu()
                {
?>
   <style type="text/css">
                h1 {font-family:Arial, Helvetica, sans-serif;
                font-size:14pt; color:#666666}
                h2 {font-family:Arial, Helvetica, sans-serif;
                font-size:10pt; color:#820000}
                a:link {color:#820000; text-decoration:none}
                a:visited {color:#820000; text-decoration:none}
                a:hover {color:#666666; text-decoration:none}
                a:active {color:#820000; text-decoration:none}                                  
   </style>
<?php
                }
}
?>

Notice that ?> precedes the actual stylesheet, and <?php follows the </style> tag. This escapes from PHP so that the content will be read as HTML and treated accordingly. Just remember that you must return to PHP to close the function and also close the class.

Alright, now comes the fun part. Let’s create index.php which will contain a menu that is formatted by our stylesheet:

<?php
 
include('mainmenu.inc');
include('styles.inc');
 
$page = new mainmenu();
$page = new stylesMainMenu();
 
?>

That’s it.

No, really, that’s it! We included mainmenu.inc and styles.inc, these provide us with the code for the menu and for our stylesheet. We then created a new object named $page by calling our constructors from within the mainmenu and stylesMainMenu classes. Objects do not always need to share their name ($page in this case), however, in order for the stylesheet to apply to the menu they need the same name.

You can make this operation as complicated or as simple as you like. In this example, we separated the classes into two files, mainmenu.inc and styles.inc, but they can both be stored in the same .inc files if you prefer. Furthermore, you can keep an entire library of stylesheets in a file called styles.inc. By making each stylesheet its own class, you can call on the attributes from that stylesheet simply by calling on its classname or contructor and including styles.inc. The same pertains to libraries of functions as well as redundant page elements such as menus, picture displays and information bars.

You can also make the menu itself dynamic by manipulating the operations within the mainmenu class. Treat these operations as instructed on page three of this lesson, and write them to conform to specific parameters and situations. For instance, you can create a conditional menu. Write the mainmenu operation so that if you are on index.php all of the buttons leading to the pages will be present in the menu, but if you are on services page, all buttons will be available except “services,” if you are on the portfolio page all buttons will be available except “portfolio”, and so on. Or perhaps you would like a different background for the menu depending on the page.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


  • None
  • Mr WordPress: Hi, this is a comment.To delete a comment, just log in, and view the posts' comments, there you will have the option to edit or delete them.

Categories

%d bloggers like this: