1

I've just started getting familiarized with OO features of PHP, and I would like to ask you something about the $this variable. First of all, if a class that I'm using the $this keyword in does not have a defined property variable foo, does that mean that using the following code:

$this->foo = 5;
echo $this->foo;

will create the foo property on the object on runtime, like in JavaScript? What is the visibility of this property?

nickf
  • 520,029
  • 197
  • 633
  • 717
Ariod
  • 5,607
  • 22
  • 71
  • 102
  • I would recommand to have a look on this so [page](http://stackoverflow.com/questions/151969/php-self-vs-this) too. – Aif Dec 06 '09 at 13:37

4 Answers4

6

Yes, this will create the foo property, and its visibility will be public (which is the default).

You could test this quite easily:

<?php
class Foo {
    public function setFoo($foo) {
        $this->foo = $foo;
    }
}

$f = new Foo();
$f->setFoo(5);
echo $f->foo;

Will print 5 with no errors.

Ben James
  • 114,847
  • 26
  • 189
  • 155
3

Worth mentioning is the __get and __set magic function. Theese methods will be called whenever an undefined property is called.

This enables a way to create pretty cool and dynamic objects. Perfect for use with webservices with unknown properties.

alexn
  • 55,635
  • 14
  • 110
  • 143
  • __construct($id) is a favorite of mine as well, allows for automatic setup of objects such as users if pulling the information from a database. $id in this case would be passed via the class declaration (e.g. $obj = new myClass($id); ) – Kaji Dec 06 '09 at 13:50
1

Yes it certainly will.

Orson
  • 14,383
  • 11
  • 52
  • 68
0

Properties can be added to any objects, independently of its class. It is also possible to write

$obj = new stdClass();
$obj->foo = 'bar';
apaderno
  • 26,733
  • 16
  • 74
  • 87