What does the dollar sign mean in PHP? I have this code:
<?php
class Building {
public $number_of_floors = 5;
private $color;
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
);
}
}
$bldgA = new Building('red');
$bldgA->describe();
?>
It seems that the $
indicates a variable like:
$number_of_floors
$color
But I get confused when I see the following:
$bldgA->describe();
$bldgA->number_of_floors;
Why are there no dollar signs before these variables?
You are right, the $ is for variable. But in a class instance, you don't use $ anymore on properties because PHP would interpret and this can cause you an error. For example, if you use
$bldgA->$number_of_floors;
this will not return the $number_of_floors property of the object but PHP will first look at the value of $number_of_floors, let's say 3 for instance, so the previous line would be
$bldgA->3;
And that will give you an error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With