Pass in value to a class with constructor in PHP

Description

The following code shows how to pass in value to a class with constructor.

Example


<?php/*w  w w  .  j  a  v  a2s  . co m*/

class Calculator {
  private $_val1, $_val2;

  public function __construct( $val1, $val2 ) {
    $this->_val1 = $val1;
    $this->_val2 = $val2;
  }

  public function add() {
    return $this->_val1 + $this->_val2;
  }

  public function subtract() {
    return $this->_val1 - $this->_val2;
  }

  public function multiply() {
    return $this->_val1 * $this->_val2;
  }

  public function divide() {
    return $this->_val1 / $this->_val2;
  }
}

$calc = new Calculator( 3, 4 );
echo "<p>3 + 4 = " . $calc->add() . "</p>";
echo "<p>3 - 4 = " . $calc->subtract() . "</p>";
echo "<p>3 * 4 = " . $calc->multiply() . "</p>";
echo "<p>3 / 4 = " . $calc->divide() . "</p>";

?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition