tags:

views:

162

answers:

5

Hello all,

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?

+6  A: 

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
+2  A: 

Yes it certainly will.

Colour Blend
A: 

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

<?php
$obj = new stdClass();
$obj->foo = 'bar';
kiamlaluno
+3  A: 

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
__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
A: 

I would recommand to have a look on this so page too.

Aif