0

I am examining some PHP code written by somebody else, and they have basically named a variable $text:

protected $text = null;

And then later in the same file, they are referring to it without the $ sign:

$this->text[$name] = new Text($age, $house);
  1. I am a little intrigued. Is this even possible? Can a variable named with a $ concatenated with some word, be referred with only the part of the identifier other than $?
  2. If yes, does it imply something special or is it a simple reference to the variable?

PS: I don't think the code is faulty because it works =s

CerebralFart
  • 3,336
  • 5
  • 26
  • 29
Solace
  • 8,612
  • 22
  • 95
  • 183
  • 1
    `$text` is not a variable, it's a class property. Properties are accessed using `$var->propertyname`. – Barmar Apr 18 '15 at 15:30
  • 1
    http://php.net/manual/en/language.oop5.basic.php – AbraCadaver Apr 18 '15 at 15:31
  • @Barmar Thank you, but does this mean we always have to access them without the `$`, or it can either be `$var->propertyname` or `$var->$propertyname`? – Solace Apr 18 '15 at 15:33
  • 1
    `$var->$propertyname means to use the value of `$propertyname` as the name of the property, e.g. `$propertyname = "text"; $this->$propertyname = "foo";` is equivalent to `$this->text = "foo";`. Please read the section of the PHP manual on OO programming. – Barmar Apr 18 '15 at 15:35

2 Answers2

1

This code is not faulty it's because it is writen in Object Oriented PHP. When you declare an attribute in a php object, in that case $text, you can later in that same class refer to that attribute as $this->text.

a_mid
  • 76
  • 6
1

That is how you access a variable (often called a property) in object oriented code.

class MyClass {
    public $name = 'Billy Bob';
    public function printName() {
        echo $this->name;
    }
}

In this example $this->name refers to the $name variable, belonging to "this" instance of the class (an instance of a class is called an object).

class MyClass { /* ... */ } // This is a class definition
$obj = new MyClass();       // This is an instance of the class, an object
Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52