My understanding was that self::thefunction() was for calling static methods and vars? For normal instance methods, you can call $this->thefunction() from within the object.
For variables, always use $this. $this is for retrieving variables within the instance of the object.
self:: or parent:: have more to do with scope within the class, rather than static vs non-static. Since functions aren’t variables or objects and instances don’t come into play, use self/parent. Self/parent simply refers to the current class.
When calling a function using self/parent, you can still call instance variables within that function using $this.
You create an instance of the class as an object in its entirety. However–functions don’t contain data–variables do.
Hence, you call an instance of a variable when you use $this.
However, to call a function from within the class, if you precede the call with self::, that indicates the scope of the call, which is inside of that class. If you’re calling a class that is inside of a class you extended, it is in the parent class, and you indicate that by calling parent::.
I wasn’t referring to instances of variables. My point was that $this refers to the current instance of a class, not to the class itself.
Although you can call the methods of a class from an instance using self::, there are situations where this might result in unwanted behaviour:
class Admin
{
public function __construct()
{
// ..
self::AddAdmin();
}
public function AddAdmin()
{
echo "Called Admin::AddAdmin";
}
}
class BlogAdmin extends Admin
{
public function AddAdmin()
{
echo "Called BlogAdmin::AddAdmin";
}
}
$admin = new BlogAdmin; // echos "Called Admin::AddAdmin"
Here, self continues to refer to the method as defined in the class where it’s defined (Admin), rather than the overridden method in BlogAdmin. If we’d used $this rather than self, the output would have been Called BlogAdmin::AddAdmin.