Return instance of the class (was "Property of class php")

Hello i am new in OOP i just want to ask How can i automatically return the instance of the class without putting a return class each function? here is my code:

class myclass
{
    function myfinalOUtput()
    { 
        //blahblah
        return new myclass(); 
    }

    function get()
    { 
        //blahblah
        return new myclass();
    }

    function set()
    { 
        //blahblah
        return new myclass();
    }
} 

i want something like:

class myclass
{
    function myfinalOUtput()
    {}

    function get()
    {}

    function set()
    {}
} 

so i can do:

$class = new myclass();
$class->get()->set()->myfinalOUtput->();

Answers


return $this;

Place that in lieu of return new myclass(); ... that's all that is required, it just passes the object back.


It's called Fluent interface and implementation for php.


What you're looking for is $this variable:

class myclass
{
    function myfinalOUtput()
    { 
        //blahblah
        return $this; 
    }

    function get()
    { 
        //blahblah
        return $this;
    }

    function set()
    { 
        //blahblah
        return $this;
    }
}

This will, at the end of the methods, return the instance, so that you could call other methods:

$class = new myclass();
$class->get()->set()->myFinalOutput();

Need Your Help