Nerede benlik ve $ this-> arasındaki fark

5 Cevap php

Nerede bir PHP sınıfı veya PHP yöntemi self ve $this-> arasındaki fark nedir?

Örnek:

Geçenlerde bu kodu gördüm.

public static function getInstance() {

    if (!self::$instance) {
        self::$instance = new PDO("mysql:host='localhost';dbname='animals'", 'username', 'password');;
        self::$instance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    return self::$instance;
}

Ama ben $this->, bir sınıfın geçerli örneği (nesne) (aynı zamanda yanlış olabilir) ifade ettiğini hatırlıyorum. Ancak, ne fark eder?

5 Cevap

$this sınıfının örneği ifade, bu doğru. Ancak, bu sınıfın tüm örnekleri için aynı statik devlet denilen şey de var. self:: bu niteliklerin ve işlevleri için erişimci olduğunu.

$this geçerli nesneye başvuruyor, self geçerli sınıfa gelir. Sınıf nesnesinin plandır. Yani bir sınıf tanımlamak, ancak nesneleri oluşturmak.

Yani diğer bir deyişle, hiçbiri-statik üyeleri veya yöntemleri statik için kendini ve bu kullanın.

$this örnek düzeyi kapsamı kullanılır oysa self sınıf düzeyi kapsamı kullanılır.

$this referans yöntemler ve bir sınıfın geçerli örneğinin özellikleri kullanılır.

self bize bir sınıfın tüm örnekleri (and even accessible outside of any instance) tarafından paylaşılan statik yöntemleri ve özellikleri, başvurmak için kullanılır.


You can take a look at Static Keyword (quoting a few lines) :

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can)

...

Static properties cannot be accessed through the object using the arrow operator ->.


And, from the page Properties (quoting) :

Within class methods the properties, constants, and methods may be accessed by using the form $this->property (where property is the name of the property) unless the access is to a static property within the context of a static class method, in which case it is accessed using the form self::$property.

self çağıran nesnenin sınıfını belirtmektedir. $this nesnenin kendisi anlamına gelir.