通过静态方法返回当前对象

Ari*_*gri 2 php

我想返回一个类的当前对象。由于 $this 变量指的是该类的当前对象,但是当我返回 this 时,我收到一个错误。

这是我的代码

class Test{
    $name;
    public static function getobj($n){ 
        $this->name; return $this; 
    }
}
$obj= Test::getobj("doc");
Run Code Online (Sandbox Code Playgroud)

Ja͢*_*͢ck 6

您不能$this在静态方法中使用,因此您必须创建该类的一个实例,然后返回:

class Test
{
    public $name;

    public static function getobj($n)
    {
        $o = new self;
        $o->name = $n;

        return $o;
    }
}

$obj = Test::getobj("doc"); // $obj->name == "doc"
Run Code Online (Sandbox Code Playgroud)