PHP: Nasıl kendi sınıfı içinde bir yöntemi kullanabilirsiniz / erişebilir?

5 Cevap

Ben kendi sınıfı içinde bir yöntemi nasıl kullanılacağını anlamaya çalışıyorum. Örnek:

class demoClass
{
    function demoFunction1()
    {
        //function code here
    }

    function demoFunction2()
    {
        //call previously declared method
        demoFunction1();
    }
}

Ben çalışıyor bulduk tek yolu ben yöntemi içinde sınıfının yeni intsnace oluşturun ve sonra onu aramak durumdur. Örnek:

class demoClass
{
    function demoFunction1()
    {
        //function code here
    }

    function demoFunction2()
    {
        $thisClassInstance = new demoClass();
        //call previously declared method
        $thisClassInstance->demoFunction1();
    }
}

but that does not feel right... or is that the way? any help?

teşekkürler

5 Cevap

$this->, bir nesne ya da self:: statik bağlam (ya da sabit bir yöntem olarak) arasında, iç.

Sadece kullanımı:

$this->demoFunction1();

$this anahtar kelime geçerli sınıf örneğine başvurmak için kullanın:

class demoClass
{
    function demoFunction1()
    {
        //function code here
    }

    function demoFunction2()
    {
        $this->demoFunction1();
    }
}

Kullan "$ this" kendisine başvurmak için.

class demoClass
{
    function demoFunction1()
    {
        //function code here
    }

    function demoFunction2()
    {
        //call previously declared method
        $this->demoFunction1();
    }
}