在类的静态函数内部调用函数


Call function inside static function of the class

在laravel框架我经常使用- Model::find($id)->orderedBy(param);

我想知道如何实现这样的表达。我是这样开始的:

 Class Test
 {
    static public function write()
    {
       echo "text no 1";
       function second()
       {
          echo "text no 2";
       }
     }
 }

现在我当我做

Test::write();

我得到"text no 1"

我想做的是:

Test::write()->second();
并得到" text no 2"

可惜我的方法行不通。

可能吗?

不好意思,我还在学习。

Model::find($id)->orderedBy(param)表示静态方法find返回对象,然后执行对象的方法orderBy

的例子:

Class Test1
{
    public function say_hello()
    {
        echo 'Hello!';
    }
}
Class Test2
{
    static public function write()
    {
        $obj = new Test1();
        return $obj;
    }
}
Test2::write()->say_hello();

Class Test
 {
    static public function write()
    {
      echo "text no 1";
      return new Test();
    }
    function second()
    {
          echo "text no 2";
    }
 }

逻辑上这是不可能的,在调用Test::write()之前您不能调用second(),您可以稍后调用它,因为之后PHP将重新声明该函数。所以你需要改变你的方法。

如果你从write()方法返回一个对象,这是可能的。

Class Test
 {
    static public function write()
    {
       echo "text no 1";
       return new Test(); //return the Test Object
    }
    function second()
    {
          echo "text no 2";
    }
 }
现在你可以调用Test::write()->second();