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
  • 537,072
  • 198
  • 649
  • 721
Ariod
  • 5,757
  • 22
  • 73
  • 103
  • 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
  • 121,135
  • 26
  • 193
  • 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
  • 57,867
  • 14
  • 111
  • 145
  • __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,981
  • 11
  • 56
  • 70
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
  • 28,547
  • 16
  • 75
  • 90