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

PHP:如何在自己的类中访问/使用方法?,php,Php,我试图弄清楚如何在自己的类中使用方法。例如: class demoClass { function demoFunction1() { //function code here } function demoFunction2() { //call previously declared method demoFunction1(); } } 我发现唯一有效的方法是在方法中创建类的新intsnac

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

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

    function demoFunction2()
    {
        //call previously declared method
        demoFunction1();
    }
}
我发现唯一有效的方法是在方法中创建类的新intsnace,然后调用它。例如:

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

    function demoFunction2()
    {
        $thisClassInstance = new demoClass();
        //call previously declared method
        $thisClassInstance->demoFunction1();
    }
}
但这感觉不对。。。还是这样? 有什么帮助吗

谢谢

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

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

因此:

使用“$this”来指代自身

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

    function demoFunction2()
    {
        //call previously declared method
        $this->demoFunction1();
    }
}
只需使用:

$this->demoFunction1();

$this->
在对象内部,或在静态上下文中(用于或来自静态方法)。

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

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

    function demoFunction2()
    {
        $this->demoFunction1();
    }
}
class demoClass
{
    function demoFunction1()
    {
        //function code here
    }

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