Home >>PHP Object Oriented >PHP Class Object

PHP Class Object

Object and Class in PHP

  • Class is a blueprint of related data members(proerties/variable) and methods(function).
  • Classes are the fundamental construct behind oops.
  • Class is a self contained independent collection of variables and functions, which work together to perform one or more specific related task.
Note: Variables within a class are called properties and functions are called methods

How to define a class

Class always start with "class" keyword. After this write class name without parentheses. Syntax
class demo

{

code to be executed

}

Eg
<?php

class demo
{

function add()

{   

$x=800;

$y=200;

$sum=$x+$y;

echo "sum of given no=".$sum."<br/>";	

}

function sub()

{

$x=1000;

$y=200;

$sub=$x-$y;

echo "Sub of given no=".$sub;	

}

}

?>

Object

  • Object is the instance of the class.
  • Once a class has been defined, objects can be created from the class through "new" keyword.
  • class methods and properties can directly be accessed through this object instance.
  • Connector(Dot operator->) symbol used to connect objects to their properties or methods.
Note: You can not access any property of the class without their object> Syntax
  $obj= new demo();

Eg
<?php

class demo

{

function add()

{   

$x=800;

$y=200;

$sum=$x+$y;

echo "sum of given no=".$sum."<br/>";

}

function sub()

{

$x=1000;

$y=500;

$sub=$x-$y;

echo "Sub of given no=".$sub;	

}

}

$obj= new demo();

$obj->add();

$obj->sub();

?>

Output Sum=1000 Subtraction=500

Ex ii

<?php

class demo

{

var   $msg="welcome";

function test()

{   

echo  "Users";    	

 }
	
}

$obj= new demo();

echo  $obj->msg;

$obj->test();
 
?>
Output welcome users

Using Parametrized method

<?php
	
class demo
{
function add($a,$b)
{   

$sum=$a+$b;

echo "Sum=".$sum."<br/>";	

}

function sub($x,$y)

{

$sub=$x-$y;

echo "Subtraction=".$sub;	

}

}

$obj= new demo();

$obj->add(800,200);

$obj->sub(1000,500);
  
?>
Output Sum=1000 Subtraction=500

Create dynamic program using oops(Numbers entered by user)

<?php

class demo

{

function add($a,$b)

{   

$sum=$a+$b;

echo "Sum=".$sum."<br/>";	

}

function sub($x,$y)

{

$sub=$x-$y;

echo "Subtraction=".$sub;	

}

}

$obj= new demo();

$obj->add($_GET['f'],$_GET['s']);

$obj->sub($_GET['f'],$_GET['s']);

?>
  
<form>

Enter first number<input type="text" name="f"/><hr/>

Enter second number<input type="text" name="s"/><hr/>

<input type="submit" value="Show result"/>

</form>

Output Sum=1500 Subtraction=500 Enter first number Enter second number

No Sidebar ads