OOP classes & instance

时间:2016-07-11 21:36:39

标签: php

For some string inputs ($age) I have to output back "you are young" ,"you are teenager" and " You are old" depends of the age inputed.

The problem with it , is that it seems my code is wrong somehow , I'm at beginning with OOP in PHP , so If you can help me with some explanations , I will be thankfully

<form action="classvsinstance.php" method="get">
    <input type="text" name="age" placeholder="age">
    <input type="submit" value="submit">
</form>

and

class Person{
    public $age;
    public function __construct($initialAge){
      // Add some more code to run some checks on initialAge
      if($initialAge < 0){
          $age = 0;
          print('Age is not valid, setting age to 0.');
      } else {
          $initialAge = $age;
      }
    }
    public  function amIOld(){

        if($age < 13){
            print("You are young.");
        }elseif(($age>=13) && ($age < 18)){
            print("You are a teenager.");
        }else{
            print("You are old");

    }
    public  function yearPasses(){
      // Increment the age of the person in here
        $age++;
    }


}

$age = $_GET['age'];
echo "Your age is " . $age . ".<br><br>";

instantiating the class

$p = new Person($age);

calling the method

$ -> amIOld();
echo "\n";

All the outputs for every number I put in the form , are "You are young".

I don't know why , and what am I doing wrong here , cuz I've tried all the ways (except the good one) .

1 个答案:

答案 0 :(得分:3)

Your construct is assiging things backwards, it should be like this:

public function __construct($initialAge){
      // Add some more code to run some checks on initialAge
      if($initialAge < 0){
          $this->age = 0;
          print('Age is not valid, setting age to 0.');
      } else {
          $this->age = $initialAge;
      }
}

You want to be assigning from $initialAge to the class variable $age, not the other way around. Then, you need to refer to the class variable with the $this keyword:

public  function amIOld(){
        if($this->age < 13){
            print("You are young.");
        }elseif(($this->age>=13) && ($this->age < 18)){
            print("You are a teenager.");
        }else{
            print("You are old");
        }
     // ^ closing brace was also missing!
}

public  function yearPasses(){
      // Increment the age of the person in here
        $this->age++;
}

Since you're working with an object, you should be using other OOP features like throwing an exception if the age is not valid. And you should definitely not be outputting messages from inside your class. Let the code outside handle that, based on the return value from the class.