Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
}
like image 218
Liam Macmillan Avatar asked Jun 15 '26 10:06

Liam Macmillan


1 Answers

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.

like image 180
CompuChip Avatar answered Jun 16 '26 23:06

CompuChip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!