Object inheritance in PHP PDF Print E-mail
Written by Bernhard Fischer   
Thursday, 01 March 2007


Object inheritance is a basic principle in object orientated programming languages.  This notional PHP example inherits the object admin_user from regular_user and extends it.

The properties username and useraddress are read from a MySQL database mydb by quering the usertable with userid as parameter.

[click to collapse source code]

 
<?php
mysql_connect("localhost");
mysql_select_db("mydb");
 
/* we fetch 2 users from the database: users with userid 1 and 2 */
$user = new regular_user;
$user->getuser(1);
$user->showuser();
 
$user = new admin_user;
$user->getuser(2);
$user->showuser();
 
class regular_user{
    var $username;
    var $useraddress;
/* fill user properties */
    function getuser($id) {
        $result = mysql_query ("SELECT * FROM usertable WHERE userid=$id");
        if($row = mysql_fetch_array($result)) {
            $this->username = $row["username"];
            $this->useraddress = $row["useraddress"];
        } else {
            $this->username = "unknown";
            $this->useraddress = "unknown";
        }
    }
/* show user information */
    function showuser() {
        print("User info<br>");
        print("Username: ".$this->username."<br>");
        print("Address: ".$this->useraddress."<br>");
    }
}
 
/* inherited admin_user */
class admin_user extends regular_user {
    function edit_address() {
        print('<form method="post" action="processing.php">Address: <input type="text" name="useraddress"
            value="'.$this->useraddress.'"></form>');
    }
}
 
mysql_close();    
?>
 
 



Add as favourites (0) | Quote this article on your site | Views: 2943

Be first to comment this article
RSS comments

Write Comment
  • Please keep the topic of messages relevant to the subject of the article.
  • Personal verbal attacks will be deleted.
  • Please don't use comments to plug your web site. Such material will be removed.
  • Just ensure to *Refresh* your browser for a new security code to be displayed prior to clicking on the 'Send' button.
  • Keep in mind that the above process only applies if you simply entered the wrong security code.
Name:
E-mail
Homepage
Title:
Comment:

I wish to be contacted by email regarding additional comments

Powered by AkoComment Tweaked Special Edition v.1.4.6
AkoComment © Copyright 2004 by Arthur Konze - www.mamboportal.com
All right reserved

Last Updated ( Friday, 18 January 2008 )
 
Next >