Mariano Guadagnini wrote:
Hy people,
I have an existential doubt regarding php classes. I have been a php
programmer for quite a long time, but never could figure out the clear
difference between using this-> or self:: when calling member functions,
wether they are private or public. I used them indistinctly and seemed
to sort the same effects, although, when working with statics classes,
self:: was the only way to access members.
Well, that's all, any can put me some light on the matter?
Thanks,
The clear difference between these two is the way you are calling (and
thus WHAT you are calling aswell).
In PHP you can use classes in 2 ways:
1. statically, you have a class defined as a collection of methods
without actual changable properties.
2. as an instance. You have a class "template" which you instantiate,
thus making what is known commonly as an object.
In case 1, we would have such code as follows:
class Foo {
static function Bar() {
echo 'I am method Bar of Class Foo';
}
}
Foo::Bar();
>> I am method Bar of Class Foo
in case 2:
class Foo {
public function Bar() {
echo 'I am method Bar of an object derived from class Foo';
}
}
$foo = new Foo;
$foo->Bar();
>> I am method Bar of an object derived from class Foo
No real difference there, right?
So, now let's imagine we want to have an object as a collection of both
methods AND properties:
if we were to use the static approach, we now have a problem:
1. you can't store and manipulate static properties (AFAIK)
2. you only have 1 class, changing it here will propagate the change
troughout your entire codebase (for this run)
If we used objects, we wouldn't have to worry about it:
Class Foo {
public $a = 1;
public function Bar() {
$this->a++;
}
}
$foo = new Foo;
echo $foo->a;
>> 1
$foo->Bar();
echo $foo->a;
>> 2
$bar = new Foo;
echo $bar->a; // (new object)!
>> 1
statically:
Class Foo {
static $a = 1;
static function Bar() {
self::a++;
}
}
echo Foo:a;
>> 1
Foo::Bar(); // will probably throw a warning, not sure of that though
echo Foo:a;
>> 1 (no change)
now, if we would want 2 different collections, each with their own value
of Foo:a, we would not be able to use the static way.
Basically what you can remember here is:
:: calls a property or method in a STATIC context (ie. without access to
the object's (if any) actual properties)
-> calls a propert or method in a DYNAMIC context (ie. WITH access to
that specific object's collection of methods and properties).
long talk, but I hope you understand the difference now.
- tul
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php