PhP Classes and Objects Explained

Class: Class is a way to organize the data. For instance , you want to write a program to display  the names of parts of a car. What you can do is you can echo out all the part names of a car. So , now you want to display the part names of 10 cars . Now echoing out sounds little bitter, isnt it? here is where object oriented concepts comes in to play. To solve the problem, we use the class concept. here int this tutorial i have created a class called coder, which contains the coders details. So we create a class template called coder. Then we create many instances of the coder class to display the details of various other coders.

Class systax:

class coder{
public $variable;
private $variable;

public fucntionS()
//your code here
} ?>

Object: Object is an instance of the class. class is like a template and we can create many copies of the class using the object.

Object Syntax:

<?php                                                                             $object1 = new coder() //here we create an on bject of type coder class using the keyword new. It means we create a object variable to connect to the class coder ?>


class coder {
public $name;
public $language;
public $position;
function showDetails($a, $b ,$b)
$this->name =$a;
$this->language =$b; //$this keyword assigns the parameter value to the variables declared as public.
$this->position =$c;
function thisTest($a)
$this->name = $a; //$this keyword here assigns the parameter to the variable name associated with function thisTest.

<title>OOP demo</title>
<h1>This ia a php object oriented demo</h1>
$person1 = new coder(); //$person1 object created with new keyword
$person1->showDetails("michael","php","junior programmer"); //using the person object , here we pass the parameters to the showDetails fucntion.
echo "<div style='background-color:blue'>".$person1->name."&nbsp&nbsp".$person1->language."</div><br/>";
echo "<div style='background-color:blue'>".$person1->name."</div>";

Other Interesting Blogs

Leave a Comment

Share via
Copy link