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

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

Program/Source Code:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.