PHP:如何在自己的类中访问/使用方法?

msp*_*pir 6 php

我试图弄清楚如何在自己的类中使用方法.例:

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

    function demoFunction2()
    {
        //call previously declared method
        demoFunction1();
    }
}
Run Code Online (Sandbox Code Playgroud)

我发现工作的唯一方法是在方法中创建类的新intsnace,然后调用它.例:

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

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

但那感觉不对......还是那样?任何帮助?

谢谢

jas*_*bar 12

$this->在对象内部,或self::在静态上下文中(来自静态方法).


Gum*_*mbo 8

您需要使用它$this来引用当前对象:

$this从对象上下文中调用方法时,伪变量可用.$this是对调用对象的引用(通常是方法所属的对象,但如果从辅助对象的上下文中静态调用该方法,则可能是另一个对象).

所以:

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

    function demoFunction2()
    {
        // $this refers to the current object of this class
        $this->demoFunction1();
    }
}
Run Code Online (Sandbox Code Playgroud)


a'r*_*a'r 5

只需使用:

$this->demoFunction1();
Run Code Online (Sandbox Code Playgroud)


Sar*_*raz 5

使用$this关键字来引用当前的类实例:

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

    function demoFunction2()
    {
        $this->demoFunction1();
    }
}
Run Code Online (Sandbox Code Playgroud)