Hacker Rank Solutions in PHP - Day 04 - Class vs. Instance

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:

  1. yearPasses() should increase the age instance variable by 1.
  2. 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..

 

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:

  1. We define a Person class with a private instance variable $age.
  2. 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.
  3. The yearPasses method increments the age by 1.
  4. 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.

Press ESC to close