3

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;
}
}
8
  • 2
    Are you instantiating the class? Commented Oct 29, 2015 at 15:20
  • 1
    new Variable();... Commented Oct 29, 2015 at 15:21
  • You have to make and instance of your class. Commented Oct 29, 2015 at 15:22
  • Do you have actual values in the post ? Commented Oct 29, 2015 at 15:23
  • 2
    I couldn't tell without seeing the bigger picture... You can pass them like that or, in my oppinion better, as input in the constructor if you don't want the class to be dependent to post values. Commented Oct 29, 2015 at 15:25

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, exactly what I was looking for. To get each variable individually, would this be a good way of doing so?: pastie.org/pastes/10516156/text
I would include validation in the constructor to make sure that arrival time and hour stay are valid, and move the calculation of the pickup time to the getter: public function get_pickupTime() { return date('H:i', (strtotime($this->arrivalTime) + $this->hourStay)); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.