Google News
logo
PHP program to define methods within the class
In the following example of PHP program that defines a class with some methods :
Program :
<?php
class Person {
    private $name;
    private $age;
    
    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
    
    public function setName($name) {
        $this->name = $name;
    }
    
    public function setAge($age) {
        $this->age = $age;
    }
    
    public function getName() {
        return $this->name;
    }
    
    public function getAge() {
        return $this->age;
    }
}

$person1 = new Person("John", 25);
$person2 = new Person("Jane", 30);

echo $person1->getName() . " is " . $person1->getAge() . " years old.<br>";
echo $person2->getName() . " is " . $person2->getAge() . " years old.<br>";

$person1->setAge(30);
echo $person1->getName() . " is now " . $person1->getAge() . " years old.<br>";
?>
Output :
John is 25 years old.
Jane is 30 years old.
John is now 30 years old.
This program defines a `Person` class with attributes `name` and `age`. It has a constructor method `__construct` which sets the initial values of `name` and `age`.

It also has setter and getter methods to modify and access the attribute values respectively. The program creates two objects of the `Person` class and accesses their attribute values using the getter methods. It then updates the age of the first person and prints the new age value.