Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the dollar sign mean in PHP? [closed]

Tags:

oop

php

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?

like image 637
user784637 Avatar asked Sep 23 '11 11:09

user784637


1 Answers

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

like image 90
Mika Andrianarijaona Avatar answered Sep 18 '22 04:09

Mika Andrianarijaona