[RESOLVED] Using This vs. Self
What is the difference between using $this->var and self::var? I've been reading tutorials, but I still don't understand.
$this->something refers to a member of this object, while self::$something refers to a member the class, which should only be used for class members that are defined to be static.
Output (note how static variable for both objects is whatever the latest value was set by either object):
public static $static_var = "Static member of class";
public $normal_var = "Normal member of objectt";
public function set($value)
self::$static_var = $value;
$this->normal_var = $value;
public function get()
echo "<p>normal: ".$this->normal_var.", static: ".self::$static_var."</p>\n";
$foo_1 = new Foo();
$foo_2 = new Foo();
$foo_1->set("This is #1");
$foo_2->set("This is #2");
normal: This is #1, static: This is #2
normal: This is #2, static: This is #2
I thought objects and classes were the same?
An object is a single instance of a class. Thus in my above example, $foo_1 and $foo_2 are two separate objects (instances) of the class Foo. Since $static_var is defined as static in the class definition, it is essentially shared by both objects, so if one object changes its value, it becomes the value for all objects (instances) of that class. On the other hand, $normal_var is not static, so if one object changes its value, that change only applies to that object, while any other object of that class maintains it's own value for that variable.
Also note that methods can be defined as static, and if so must only reference other class members statically (i.e. such static methods cannot use $this, only self). This means you can call any static method or variable without instantiating an object, such as in the above example you could reference Foo::$static_var directly in the code without ever using "new" to create an object of that class.
PS: If the difference between class and object is still confusing to you, try this tutorial. This is an essential concept you want clear in you mind before going too much further with OOP. (Even though that web tutorial is Java-oriented, the concepts are the same, and the few code examples are generally almost completely compatible with PHP code.
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)