30 Days of Code - Day 4: Class vs. Instance
Task
Write a Person class with an instance variable, age, and a constructor that takes an integer, initialAge, as a parameter. The constructor must assign initialAge to age after confirming the argument passed as initialAge is not negative; if a negative argument is passed as initialAge, the constructor should set age to 0 and print Age is not valid, setting age to 0.
. In addition, you must write the following instance methods:
- yearPasses() should increase the age instance variable by 1.
- amIOld() should perform the following conditional actions:
- If age < 13, print
You are young.
. - If age >= 13 and age < 18, print
You are a teenager.
. - Otherwise, print
You are old.
.
- If age < 13, print
Solution in PHP:
You can create the Person
class as described with the instance variables, constructor, and instance methods. Here's a PHP implementation of the Person
class:
<?php
class Person{
public $age;
public function __construct($initialAge){
if ($initialAge < 0) {
$this->age = 0;
echo "Age is not valid, setting age to 0.\n";
} else {
$this->age = $initialAge;
}
}
public function amIOld(){
if ($this->age < 13) {
echo "You are young.\n";
} elseif ($this->age >= 13 && $this->age < 18) {
echo "You are a teenager.\n";
} else {
echo "You are old.\n";
}
}
public function yearPasses(){
$this->age++;
}
}
$T = intval(fgets(STDIN));
for($i=0;$i<$T;$i++){
$age=intval(fgets(STDIN));
$p=new Person($age);
$p->amIOld();
for($j=0;$j<3;$j++){
$p->yearPasses();
}
$p->amIOld();
echo "\n";
}
?>
In this code:
- We define a
Person
class with a private instance variable$age
. - In the constructor, we check if the initial age provided is negative. If it's negative, we set the age to 0 and print a message. Otherwise, we set the age to the provided value.
- The
yearPasses
method increments the age by 1. - The
amIOld
method checks the age and prints an appropriate message based on the conditions mentioned in the task description.
Finally, we create an instance of the Person
class, set the initial age, and call the amIOld
method to print the initial message. Then, we call yearPasses
to increase the age and call amIOld
again to print the updated message.