I’m new to oop and was surprised to see that code that worked properly in procedural programming,
<?php
$number_of_floors = 5;
$stairs_per_floor= 10;
echo $total_stairs= $number_of_floors*$stairs_per_floor;
?>
Lead to an error when included inside of a class:
<?php
// Class
class Building {
// Object variables/properties
public $number_of_floors = 5; // These buildings have 5 floors
public $stairs_per_floor= 10;
public $total_stairs= $number_of_floors*$stairs_per_floor;
private $color;
// Class constructor
public function __construct($paint) {
$this->color = $paint;
}
public function describe() {
printf('This building has %d floors. It is %s in color.',
$this->number_of_floors,
$this->color
);
}
}
// Build a building and paint it red
$bldgA = new Building('red');
// Tell us how many floors these buildings have, and their painted color
$bldgA->describe();
?>
If you remove
public $total_stairs= $number_of_floors*$stairs_per_floor;
Everything works.
Are you not allowed to write arithmetic expressions inside of a class if they are outside of a function? What type of code that interprets correctly in procedural programming will cause an error when included in a class (outside of a function)?
You can not do the operation at the time of defining them. Instead you should add this to your constructor and do:
Furthermore I advise you to use the generally accepted coding standards of PHP which would mean, not to use underscores in variable names.
Even more important is the choice of meaningful and readable variables names. So $bldgA should be:
$buildingA