Search code examples
phpechoconstruct

PHP construct not echoing variables


I'm new to PHP so still getting grips of how constructs work and I'd appreciate some help!

The following code is failing to echo the variables $arrivalTime and $hourStay:

class Variable {

public $arrivalTime;
public $hourStay;   

public function __construct() {
    $this->arrivalTime = $_POST['arrivalTime'];
    $this->hourStay = $_POST['hourStay'];

    echo $this->arrivalTime;
    echo $this->hourStay;
}
}

Solution

  • You need to instantiate the class, by calling new Variable() somewhere in your code. However, in general it is better to not have your class depend on the post variables, but pass them in through the constructor:

    class Variable {
    
      public $arrivalTime;
      public $hourStay;   
    
      public function __construct($arrivalTime, $hourStay) {
          // TODO: Check if the values are valid, e.g.
          // $arrivalTime is a time in the future 
          // and $hourStay is an integer value > 0.
          $this->arrivalTime = $arrivalTime;
          $this->hourStay = $hourStay;
      }
    
      public function print() {
          echo $this->arrivalTime;
          echo $this->hourStay;
      }
    }
    
    $var = new Variable($_POST['arrivalTime'], $_POST['hourStay']);
    $var->print();
    

    Also note how I took the generation of output away from the constructor. Its only task should be to initialize the object to a valid state. Processing input or generating output is not its responsibility.