PHP Classes | PHP Class Methods

PHP Classes

Last Updated by Yogesh Khanna 12-Mar-20

0 1687


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 symbol $, followed by the name of the variable. And then we need to create an 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.

After creating class, we need to create object to access the functionalities of that class. You can create an object either by using the name of the class or by using constructor of that class.

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;

/* 
we can also create an object only by class name
$food = new all_foods;
*/

echo  ' I love ' .  $food->great_foods . ' . ' ;
?>

Result:

PHP Classes

Now we create another example for class in php. we print the output directly 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 Classes


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. We use this keyword to assign or get value from functions

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 Classes

We also used set and get value outside the function. In this way we can assign different values to a variable inside the 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 Classes

For Any Technical Question or Suggestions, you can feel free contact to us by comment box

Our team always ready to serve you.


Share:


Discount Coupons



Leave a Reply


Comments
    Waiting for your comments