Php 通过静态方法返回当前对象
我想返回类的当前对象。由于$this变量引用该类的当前对象,但当我返回它时,我得到一个错误 这是我的密码Php 通过静态方法返回当前对象,php,Php,我想返回类的当前对象。由于$this变量引用该类的当前对象,但当我返回它时,我得到一个错误 这是我的密码 class Test{ $name; public static function getobj($n){ $this->name; return $this; } } $obj= Test::getobj("doc"); 恐怕你不能这样做。静态方法不存在该类的实例。您可以调用静态方法,而不需要任何实例。没有$this,因为没有实例。如果您
class Test{
$name;
public static function getobj($n){
$this->name; return $this;
}
}
$obj= Test::getobj("doc");
恐怕你不能这样做。静态方法不存在该类的实例。您可以调用静态方法,而不需要任何实例。没有
$this
,因为没有实例。如果您想要一个,则需要创建一个:
$obj = new Test();
您可能想做的事情如下:
class Test
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
}
现在,您可以创建该类的实例,如下所示:
$obj = new Test('doc');
一些评论提到了一种称为单例模式的东西。如果您知道您只希望一个类的一个实例存在,那么您可以使用它。它的工作原理是将该实例存储在类的静态变量中:
class A()
{
/**
* The instance itself
* @var A
*/
private static $instance;
/**
* Constructor. Private so nobody outside the class can call it.
*/
private function __construct() { };
/**
* Returns the instance of the class.
* @return A
*/
public static function getInstance()
{
// Create it if it doesn't exist.
if (!self::$instance) {
self::$instance = new A();
}
return self::$instance;
}
}
不能在静态方法中使用
$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"
使用Singleton模式?我不想这么说,但是您的代码没有编译。“当我返回这个时,我得到一个错误”-这是?如果您需要获取类的对象,它很简单$obj=new Test()@弗雷德二世-是的,你完全正确:)@arifhussainshigri哦,糟糕,打字错误=p