English (United Kingdom)Deutsch (DE-CH-AT)
Home Programming PHP Object inheritance in PHP
Object inheritance in PHP PDF Print E-mail
Thursday, 01 March 2007 04:58

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.


 
<?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();    
?>
 

 

 

Search

Login