mspir
mspir

Reputation: 1734

PHP: How can I access / use a method within its own class?

I am trying to figure out how to use a method within its own class. example:

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

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

The only way that I have found to be working is when I create a new intsnace of the class within the method, and then call it. Example:

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?

thanks

Upvotes: 6

Views: 7663

Answers (5)

Sarfraz
Sarfraz

Reputation: 382696

Use $this keyword to refer to current class instance:

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

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

Upvotes: 5

jasonbar
jasonbar

Reputation: 13461

$this-> inside of an object, or self:: in a static context (either for or from a static method).

Upvotes: 16

a'r
a'r

Reputation: 36999

Just use:

$this->demoFunction1();

Upvotes: 5

Jage
Jage

Reputation: 8086

Use "$this" to refer to itself.

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

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

Upvotes: 4

Gumbo
Gumbo

Reputation: 655239

You need to use $this to refer to the current object:

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

So:

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

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

Upvotes: 8

Related Questions