How to Create Class In PHP

Introduction

I will describe creation of a class in PHP. A class is a blueprint for the object that informs the compiler what method property will exist if an object is created from this class. A class is just like a function of PHP. I am describing how to create a simple class in PHP. A class in Object Oriented Programming (OOP) and the Object Oriented Programming addin in PHP for security purposes was introduced in PHP 5.3 and in OOP. It's not in PHP 4. This example will show the methods.

Example

<?php

class fruits

{

var $mango= 'Yellow';

var $orange= 'orange';

}

// here instantiates the class

$veg = new fruits();

//new keyword is object

echo "This fruits is  " .$veg->mango . " mango";

?>

 

Output


creating1 class in php.jpg

We used a new keyword here to create an object in our fruits class and the dollar "veg" is an object. Here in this example, we have the simple results showing the fruit's color.

Calling Attributes

As well as calling the attribute and modifying the attribute, in the same way the mangos are incremented. For the example if we want the mango attribute to be increased by say, one, so that mangos now equals three, then this is what we do:

<?php

class fruits

{

var $mango=2;

var $orange=2;

}

$veg = new fruits();

$veg->mango++;

//Here increases mango

echo "The " .$veg->mango." mango";

?>

 

Output

creating in class.jpg

You can see how to use attributes and how to use variables.


Similar Articles