Addition program using oops

The output will be 0…I dont know what is the error in return statement…

[php]

<?php class abc { public $x; public $y; public $z; public function add() { return $this->x+$this->y; } } $t = new abc(); $t->add(); $k=$t->add(1,16); echo $k; ?>

[/php]

This might help you comprehend a little bit of PHP OOP ( I would recommend getting a good book on PHP OOP or finding a video tutorial on PHP OOP):

[php]<?php

class AddNumbers {

protected $x = 0;
protected $y = 0;
protected $z = 0;

// Add the variables up and return the sum:
public function add() {

    return $this->x + $this->y + $this->z;
}

// Set $x value:
public function setX($x) {
    $this->x = $x;
}
// Set $y value:
public function setY($y) {
    $this->y = $y;
}
// Set $z value:
public function setZ($z) {
    $this->z = $z;
}

}

// Set $x value:
$x = 1;
// Set $y value:
$y = 16;

// Create a new instance:
$add = new AddNumbers();

$add->setX($x); // Sets x:
$add->setY($y); // Sets y:

$sum = $add->add(); // Calculate sum:

// Output addition:
echo $x . ’ + ’ . $y . ’ = ’ . $sum . ‘
’;
[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service