I guess there may not be any difference but personal preference, but when reading various PHP code I come across both ways to access the methods class.
What is the difference:
class Myclass { public static $foo; public static function myMethod () { // between: self::$foo; // and MyClass::$foo; } }
PHP new self vs new static: Now that we changed the code in our example to use static instead of self, you can see the difference is that self references the current class, whereas the static keyword allows the function to bind to the calling class at runtime.
self is used to access static or class variables or methods and this is used to access non-static or object variables or methods. So use self when there is a need to access something which belongs to a class and use $this when there is a need to access a property belonging to the object of the class.
The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.
You can't use $this inside a static function, because static functions are independent of any instantiated object. Try making the function not static. Edit: By definition, static methods can be called without any instantiated object, and thus there is no meaningful use of $this inside a static method.
(Note: the initial version said there was no difference. Actually there is)
There is indeed a small diference. self::
forwards static calls, while className::
doesn't. This only matters for late static bindings in PHP 5.3+.
In static calls, PHP 5.3+ remembers the initially called class. Using className::
makes PHP "forget" this value (i.e., resets it to className
), while self::
preserves it. Consider:
<?php class A { static function foo() { echo get_called_class(); } } class B extends A { static function bar() { self::foo(); } static function baz() { B::foo(); } } class C extends B {} C::bar(); //C C::baz(); //B
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With