PHP program to create a class with setter and getter functions

Here, we are going to learn how to create a class with setter and getter functions in PHP?
Submitted by Nidhi, on November 10, 2020 [Last updated : March 13, 2023]

Class with Setter and Getter Functions

Here, we will define a class Sample with setter and getter functions.

PHP code to create a class with setter and getter functions

The source code to create a class with setter and getter functions is given below. The given program is compiled and executed successfully.

<?php
//PHP program to create a class with
//setter and getter functions.
class Sample
{
    private $A;
    private $B;

    public function GetA()
    {
        return $this->A;
    }

    public function GetB()
    {
        return $this->B;
    }

    public function SetA($A)
    {
        $this->A = $A;
    }

    public function SetB($B)
    {
        $this->B = $B;
    }
}

$S = new Sample();

$S->SetA(10);
$S->SetB(20);

echo "A: " . $S->GetA() . '<br>';
echo "B: " . $S->GetB() . '<br>';
?>

Output

A: 10
B: 20

Explanation

In the above program, we created a class Sample that contains two data members $A and $B. Here we created setter functions SetA(), SetB() and getter functions GetA() and GetB().

The setter functions SetA() and SetB() are used to set the values of $A and $B. The getter functions GetA() and GetB() are used to get the values of $A and $B.

After that, we created the object $S of Sample class and then called the setter and getter functions using the object.

PHP Class & Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.