Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

self:: vs className:: inside static className methods in PHP

Tags:

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;     } } 
like image 340
raveren Avatar asked Aug 13 '10 22:08

raveren


People also ask

What is difference between self and static in PHP?

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.

What is self :: in PHP?

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.

What is the difference between self and this?

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.

How use $this in static method in PHP?

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.


1 Answers

(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 
like image 99
Artefacto Avatar answered Sep 19 '22 05:09

Artefacto