PHP Classes

A class is the primary building block of a program.  It is basically a collection of functions and variables. We can create functions using keyword function and variables using var. And then we need to create and object.

Suppose you need to create an object of a class named Bird in our program, then first need to create a class called Bird, which contains all the functionalities or behaviors and properties of any bird.

Classes allow you to define a self-contained environment wherein, we control all the methods that can be applied to a given set of data and also control access to the data.

How Class work?

<?php

// firstly create a class

class all_foods
{
public $great_foods=‘pizza’;
}

//use ‘new’ keyword

$food = new all_foods;
echo  ‘ I love ‘ .  $food->great_foods . ‘ . ‘ ;

?>

Result:

Now we create another example for class in php. we print the output in this way also.

PHP Code:

<?php

class MyphpClass
{
public $php_class = "PHP class Session";
}
$object = new MyphpClass;

// Output display in another way

echo $object->php_class;

Result:

PHP Class Session

CLASS METHODS:

We defined a class method using a set and get value functions. in this way object are defined with in a class as methods.

For Example:

class MyphpClass_1

{
public $php_property = "I LIKE PHP";

// set which value you print

public function set_php_Property($enter_value)
{
$this->php_property = $enter_value;
}

// get value function call

public function get_php_Property()
{
return $this->php_property . "<br />";
}
}
$value = new MyphpClass_1;
echo $value->php_property;

// value print

Result:

PHP Class Session Example

We also used set and get value outside the function. In this way another output are create using set and get function.

class MyphpClass_2
{
public $php_property = "I LIKE PHP";
public function set_php_Property($enter_value)
{
$this->php_property = $enter_value;
}
public function get_php_Property()
{
return $this->php_property . "<br />";
}
}
$value = new MyphpClass_2;

// Get the property value

echo $value->get_php_Property();

// Set a new property value

$value->set_php_Property("I LIKE MYSQL");

// value change print

echo $value->get_php_Property();

Result:

php-class-session-2

For Any Technical Question or Suggestions, you can feel free contact to us by comment box, Our Team always ready to serve you.


Leave a Reply

avatar
  Subscribe  
Notify of