0

您好,我是 OOP 的新手,我只想问如何在不为每个函数放置返回类的情况下自动返回类的实例?这是我的代码:

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

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

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

我想要类似的东西:

class myclass
{
    function myfinalOUtput()
    {}

    function get()
    {}

    function set()
    {}
} 

所以我可以这样做:

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

3 回答 3

3
return $this;

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

于 2012-06-11T06:48:48.623 回答
2

它被称为php的Fluent 接口和实现。

于 2012-06-11T06:56:56.033 回答
0

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();
于 2012-06-11T06:48:50.490 回答