Skip to main content

Inheritance in object-oriented PHP

PHP oops concept :

One of the main advantages of object-oriented programming is the ability to reduce code duplication with inheritance,
code duplication means reduces same function/method write multiple time.code duplication occurs when same code write more than one.
In inheritance we have one parent class and other is child class, parent class having properties can access child class.


Code :


Demo:


How to create classes?
In order to create a class, we group the code that handles a certain topic into one place. For example, we can group all of the code that handles the users of a blog into one class, all of the code that is involved with the publication of the posts in the blog into a second class, and all the code that is devoted to comments into a third class.


Syntax:
class <Class-name>() { //write something code::- }

Eg:


class MyCompany
{
$empID=”10”;
$empName=”Disuza Jen”;
$empMobile=”1234567890”;
}

Object of class create :
we can use object of class and access all properties of thos class.
In order to work with a class, we need to create an object from it. In order to create an object, we use the new keyword.

For example:

$objName=new MyCompany;



how to extend child class from parent class :
Example :

class child extend MyCompany
{
//Write code here :
}

Following basic example of company and company manufacture four wheeler,
Example :

<?php class Car
{
 private $model;


 public function CarModels($model)
 {
  $this->model->$model;
 }

 public function CarShow()
 {
  return “Model is : ”.$this->model;
 }

}


class CarType extend Car
 {
  //no need code in child class::-
 }

$carttype=new CarType();
$carttype-> CarModels(“Maruti”);
echo $carttype->hello();?>




Example run as :



please create following file strcture for implementing inheritance :

1-header.php,
2-footer.php,
3-index.php,
4-inderitance.js,
5-ChildInherit.php,
6-error.css,
7-jquery.validate.js,

1-header.php :
header file include following html code, header file link only boostrap and validation file link,
code :


<!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>PHP Inheritance Program</title>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
 <link href="error.css" rel="stylesheet">
 <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous">
 </script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
 <script src="jquery.validate.js"></script>
 <script src="inderitance.js"></script>
</head>
<body>
<!-- start:header -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<a class="navbar-brand" href="#">Free Teachnology</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home <span class="sr-only"></span></a></li>
<li><a href="#">About us</a></li>
<li><a href="#">Contact us</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>>


2-footer.php :
footer file include social media link :

Code :

<!-- Start::footer -->
<footer>
<div class="footer footer-bottom">
<div class="container">
<p class="pull-left"> Copyright © <?php echo date('Y');?>. Design and Develop by - Disuza Jen. </p>
<div class="pull-right">
<ul class="nav nav-pills payments">
<li><i class="fa fa-facebook"></i></li>
<li><i class="fa fa-google"></i></li>
<li><i class="fa fa-twitter"></i></li>
<li><i class="fa fa-link"></i></li>
</ul>
</div>
</div>
</div>
<!--/.footer-bottom-->
</footer>
<!-- End::footer -->
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css">
<br>
<!--Start:: if success ajax call then show message -->
<div id="demo"></div>
<!--End:: if success ajax call then show message -->
</body>
</html>


3-inderitance.js :
it files include validation code of jquery files,
select box validation and if form submit successfully then ajax function call and show result as per select option select.

Code :

jQuery(document).ready(function () {
$("#signupFrom").validate({
rules: {
carbrand: {
required: true,
},
carmodel: {
required: true,
},
carcolour: {
required: true,
},
},
messages: {
carbrand: {
required: "* Please select car brand.",
},
carmodel: {
required: "* Please select car model.",
},
carcolour: {
required: "* Please select car colour.",
},
},

submitHandler : function(form) {
var carbrand = $.trim($('#carbrand').val());
$.ajax({
type: "POST",
url: "ChildInherit.php",
async: true,
data: {carbrand:carbrand},
success: function(html) {
var result=$.parseJSON(html);
if(result.status==0) {
$("#shows").hide();
alert('Something goes wrong.');
alert('Enter correct value.');
} else if(result.status==1) {
$("#shows").show();
$("#carbrand_name").html(result.carname);
$("#carmodel").html(result.car_model);
$("#car_colour").html(result.car_colour);
} else {
alert('Something goes wrong.');
}
}
});
}
});
});


submit handler function handle form submit or not, following function of ajax show response -


var carbrand = $.trim($('#carbrand').val());
$.ajax({
type: "POST",
url: "ChildInherit.php",
async: true,
data: {carbrand:carbrand},
success: function(html) {
var result=$.parseJSON(html);
if(result.status==0) {
$("#shows").hide();
alert('Something goes wrong.');
alert('Enter correct value.');
} else if(result.status==1) {
$("#shows").show();
$("#carbrand_name").html(result.carname);
$("#carmodel").html(result.car_model);
$("#car_colour").html(result.car_colour);
} else {
alert('Something goes wrong.');
}
}
});


above js file ajax file reponse result status check 1 and 0 if status is get 1 then set value of carmodel,carbrand and car colour.

4-ChildInherit.php :
ChildInherit.php file is form submit action file call :

Code :

<?php
/*
*Start:: inheritance of car and car model with colour,brand,
Developed by : disuza jen
Mail id: disuzajen@gmail.com
*
*/


//Post value ::-
$carbrand_post=$_POST['carbrand'];
class Car
{
public function carBrand()
{
$carbrand=array('Maruti','Mahindra','BMW','SKODA');
return $carbrand;
}

public function Maruti()
{
$maruti=array('color'=>'pink','model'=>'D4');
return $maruti;
}

public function Mahindra()
{
$Mahindra=array('color'=>'white','model'=>'A1');
return $Mahindra;
}

public function BMW()
{
$Mahindra=array('color'=>'Pink','model'=>'C1');
return $Mahindra;
}

public function SKODA()
{
$Mahindra=array('color'=>'Black','model'=>'B1');
return $Mahindra;
}
}

class ChildInherit extends Car
{
}
$obj =new ChildInherit();
$final= $obj->carBrand();
if(in_array($carbrand_post, $final)){
$finals= $obj->$carbrand_post();
$result=array('status'=>1,'carname'=>$carbrand_post,'car_colour'=>$finals['color'],'car_model'=>$finals['model']);
echo json_encode($result);
exit();
} else {
$result=array('status'=>"0");
echo json_encode($result);
exit();
}

?>

Now above example show inheritance of class mail class is Car and child class ChildInherit this call inhert form car and access all porperties of particular class :

Parent class code is :

class Car
{
public function carBrand()
{
$carbrand=array('Maruti','Mahindra','BMW','SKODA');
return $carbrand;
}
public function Maruti()
{
$maruti=array('color'=>'pink','model'=>'D4');
return $maruti;
}

public function Mahindra()
{
$Mahindra=array('color'=>'white','model'=>'A1');
return $Mahindra;
}

public function BMW()
{
$Mahindra=array('color'=>'Pink','model'=>'C1');
return $Mahindra;
}

public function SKODA()
{
$Mahindra=array('color'=>'Black','model'=>'B1');
return $Mahindra;
}
}


parent class define car brand name and brand name method define properties as per car brand model select wise. Main model Maruti,Mahindra,BMW,SKODA,
child class is and child class extends form parent class :

Code :

class ChildInherit extends Car
{
}

child class create object and thoes object call parent class method and properties ,

Code :

$obj =new ChildInherit();
$final= $obj->carBrand();

using object you can access parent class of function. I hope that you can understand and enjoy my code if you like my code please comment

Comments

Popular posts from this blog

using PDO database connection add,update,delete,edit operation

PDO advantage : 1-Object Oriented 2-Bind parameters in statements (security) 3-Allows for prepared statements and rollback functionality (consistency) 4-Throws catcheable exceptions for better error handling (quality) 5-Exception mode; no need to check error state after each API call. It's best to tell PDO how you'd like the data to be fetched. You have the following options: 1-PDO::FETCH_ASSOC: returns an array indexed by column name. 2-PDO::FETCH_BOTH: (default):returns an array indexed by both column name and number. 3-PDO::FETCH_BOUND:Assigns the values of your columns to the variables set with the ->bindColumn() method. 4-PDO::FETCH_CLASS: Assigns the values of your columns to properties of the named class. It will create the properties if matching properties do not exist. 5-PDO::FETCH_INTO:Updates an existing instance of the named class. 6-PDO::FETCH_LAZY: Combines. 7-PDO::FETCH_BOTH/PDO:FETCH_OBJ, creating the object variable names as t...

Profile Share Fixing the Thumbnail Image, Title and Description for Shared Links

Profile Share Fixing the Thumbnail Image, Title and Description for Shared Links user want to share any information then use following code  and read step by step Profile Share Fixing the Thumbnail Image, Title and Description for Shared Links if you want share profile on following social link : 1-Facebook 2-twitter.com 3-LinkedIn 4-google +, Code link : https://drive.google.com/open?id=1IzTZZh_0euDqFSHL_vPRiQePlNTw3h-q Demo link : http://freeteachnology.hol.es/socialshare/ To modify a page's thumbnail image, description, and additional metadata for these services, you can provide meta tags in the HTML code of the page.Implementing Open Graph Meta Tags You can implement meta tags in a number of ways. In content management systems might  be allow you to modify a page's meta tags , then use following code in meta section of your project code, <link href="bootstrap.min.css" rel="stylesheet"> <link href="bootstrap-tour.m...

GUID for globally unique identifier

How to create GUID in php 1-guid stands for globally unique identifier generally used to create random unique strings in php, create access token in php 2-Mostly use of GUID for generating access token, generate unique id, generating unique string in php. Using this article how to create guide in php you can create a random string for any use to keep unique 3-GUID consists of alphanumeric characters only and is grouped in five groups separated by hyphens as seen in this example: 3F2504E0-4F89-11D3-9A0C-0305E82C3301 Eg:- <?php /** * Generate Globally Unique Identifier (GUID) * E.g. 2EF40F5A-ADE8-5AE3-2491-85CA5CBD6EA7 * * @param boolean $include_braces Set to true if the final guid needs * to be wrapped in curly braces * @return string */ function generateGuid($include_braces = false) { if (function_exists('com_create_guid')) { if ($include_braces === true) { return com_create_guid(); } else { return substr(com_cr...